diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 00000000..b634d85f --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.pdf filter=lfs diff=lfs merge=lfs -text diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 476d040a..9869f8ad 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -18,7 +18,7 @@ jobs: persist-credentials: false - uses: actions/setup-python@v6 with: - python-version: '3.10' + python-version: '3.11' - name: Install Rust run: rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy --no-self-update - name: Rust formatting diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 83b986b5..658565c2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -27,7 +27,7 @@ jobs: persist-credentials: false - uses: actions/setup-python@v6 with: - python-version: '3.10' + python-version: '3.11' - name: Install Rust run: rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --no-self-update - uses: Swatinem/rust-cache@v2 diff --git a/.github/workflows/wheels-build.yml b/.github/workflows/wheels-build.yml index 0dc0d57f..c4d89b5a 100644 --- a/.github/workflows/wheels-build.yml +++ b/.github/workflows/wheels-build.yml @@ -43,7 +43,7 @@ jobs: - uses: actions/setup-python@v6 if: runner.os != 'Linux' with: - python-version: '3.10' + python-version: '3.11' - name: Set up native build tools if: runner.os != 'Linux' run: | @@ -66,14 +66,14 @@ jobs: -e PLATFORM -e RUSTUP_TOOLCHAIN -e CARGO_PROFILE_DEV_DEBUG \ -e CARGO_PROFILE_TEST_DEBUG -e CARGO_INCREMENTAL -e CARGO_BUILD_JOBS \ "$IMAGE" bash -euo pipefail -c ' - export PATH="/opt/python/cp310-cp310/bin:$HOME/.cargo/bin:$PATH" + export PATH="/opt/python/cp311-cp311/bin:$HOME/.cargo/bin:$PATH" export CARGO_TARGET_DIR=/tmp/cqlib-manylinux-target curl --proto "=https" --tlsv1.2 -sSf https://sh.rustup.rs -o /tmp/rustup.sh sh /tmp/rustup.sh -y --profile minimal --default-toolchain "$RUSTUP_TOOLCHAIN" python -m pip install maturin==1.14.1 packaging==25.0 tomli==2.2.1 cmake==3.31.6 cargo test --locked -p cqlib-core -p binding-c -p cqlib python tools/ci.py release --platform "$PLATFORM" - for version in 311 312 313 314; do + for version in 312 313 314 315; do /opt/python/cp$version-cp$version/bin/python -m pip install packaging==25.0 /opt/python/cp$version-cp$version/bin/python tools/ci.py wheel-test done @@ -81,8 +81,8 @@ jobs: - uses: actions/setup-python@v6 if: runner.os != 'Linux' with: - python-version: '3.11' - - name: Test the same wheel on Python 3.11 + python-version: '3.12' + - name: Test the same wheel on Python 3.12 if: runner.os != 'Linux' run: | python -m pip install packaging==25.0 @@ -90,8 +90,8 @@ jobs: - uses: actions/setup-python@v6 if: runner.os != 'Linux' with: - python-version: '3.12' - - name: Test the same wheel on Python 3.12 + python-version: '3.13' + - name: Test the same wheel on Python 3.13 if: runner.os != 'Linux' run: | python -m pip install packaging==25.0 @@ -99,8 +99,8 @@ jobs: - uses: actions/setup-python@v6 if: runner.os != 'Linux' with: - python-version: '3.13' - - name: Test the same wheel on Python 3.13 + python-version: '3.14' + - name: Test the same wheel on Python 3.14 if: runner.os != 'Linux' run: | python -m pip install packaging==25.0 @@ -108,8 +108,8 @@ jobs: - uses: actions/setup-python@v6 if: runner.os != 'Linux' with: - python-version: '3.14' - - name: Test the same wheel on Python 3.14 + python-version: '3.15' + - name: Test the same wheel on Python 3.15 if: runner.os != 'Linux' run: | python -m pip install packaging==25.0 @@ -131,7 +131,7 @@ jobs: persist-credentials: false - uses: actions/setup-python@v6 with: - python-version: '3.10' + python-version: '3.11' - name: Install build tools run: | rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --no-self-update diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 9287db4d..a77d3f50 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -17,7 +17,7 @@ jobs: persist-credentials: false - uses: actions/setup-python@v6 with: - python-version: '3.10' + python-version: '3.11' - run: python -m pip install packaging==25.0 tomli==2.2.1 - name: Check tag and component versions env: diff --git a/.typos.toml b/.typos.toml index fd32352e..80d170cf 100644 --- a/.typos.toml +++ b/.typos.toml @@ -1,3 +1,7 @@ +[default] +# Unicode decimal-number category in regular expressions. +extend-ignore-re = ['\\p\{Nd\}'] + [default.extend-words] ket = "ket" bra = "bra" diff --git a/CONTRIBUTING.CN.md b/CONTRIBUTING.CN.md index be94d093..107cb385 100644 --- a/CONTRIBUTING.CN.md +++ b/CONTRIBUTING.CN.md @@ -63,7 +63,7 @@ docs/ 文档相关文件 本项目当前要求: - Rust 1.89+ -- Python 3.10+ +- Python 3.11+ - C 11+ 工具链,用于 C 绑定相关开发 建议使用 `rustup` 管理 Rust 工具链,并使用 Python 虚拟环境隔离开发依赖。 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a1e5dd35..85b899e6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -63,7 +63,7 @@ Keep common changes scoped to the relevant module when possible, and avoid combi The project currently requires: - Rust 1.89+ -- Python 3.10+ +- Python 3.11+ - A C 11+ toolchain for C binding development We recommend using `rustup` for Rust toolchains and a Python virtual environment for Python dependencies. diff --git a/Cargo.lock b/Cargo.lock index ee324102..5978012b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -165,8 +165,9 @@ checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" [[package]] name = "binding-c" -version = "0.1.0-beta.1" +version = "0.1.0-beta.7" dependencies = [ + "bitvec", "cbindgen", "cqlib-core", "libc", @@ -177,7 +178,7 @@ dependencies = [ [[package]] name = "binding-python" -version = "2.0.0-beta1" +version = "2.0.0-beta7" dependencies = [ "chrono", "cqlib-core", @@ -464,14 +465,14 @@ dependencies = [ [[package]] name = "cqlib" -version = "0.1.0-beta.1" +version = "0.1.0-beta.7" dependencies = [ "cqlib-core", ] [[package]] name = "cqlib-core" -version = "0.1.0-beta.1" +version = "0.1.0-beta.7" dependencies = [ "approx", "bitvec", diff --git a/Cargo.toml b/Cargo.toml index 84695230..28eafae5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,7 +8,7 @@ members = [ resolver = "2" [workspace.package] -version = "0.1.0-beta.1" +version = "0.1.0-beta.7" edition = "2024" rust-version = "1.89" license = "Apache-2.0" diff --git a/README.CN.md b/README.CN.md index 3b5d4eec..999bbda7 100644 --- a/README.CN.md +++ b/README.CN.md @@ -6,7 +6,7 @@ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE.txt) [![Rust](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org) -[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org) +[![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org) [![C](https://img.shields.io/badge/c-11%2B-lightgrey.svg)](https://en.cppreference.com/w/c/11) [English](README.md) @@ -16,7 +16,7 @@ ## 概述 Cqlib 是一个高性能量子计算 SDK,为量子程序的构建、优化与执行提供统一基础。核心采用 Rust 实现,兼顾极致性能与内存安全,并原生支持 -Python 3.10+ 和 C 11+ 语言接口。 +Python 3.11+ 和 C 11+ 语言接口。 Cqlib 从底层设计兼顾科研与生产需求,覆盖量子计算全流程:从线路构建与参数化,到多层 IR 变换、基于规则的编译优化 Pass,再到搭载噪声模型的真实设备模拟,并内置零噪声外推(ZNE)和虚拟蒸馏(Virtual @@ -24,6 +24,8 @@ Distillation)等误差缓解技术。其模块化设计支持独立使用各 了解更多请访问 **[qc.zdxlz.com/cqlib](https://qc.zdxlz.com/cqlib)**。 +**[阅读白皮书](docs/whitepaper/Cqlib.pdf)** —— 一份文档讲清 Cqlib 的设计理念、系统架构与技术细节。 + ## 核心特性 - **量子线路构建** — 直观的 API 用于构建、组合和参数化量子线路 @@ -136,12 +138,12 @@ int main(void) { | 语言 | 最低版本 | 绑定技术 | |--------|------|-------------------| | Rust | 1.89 | 原生 | -| Python | 3.10 | PyO3 (abi3-py310) | +| Python | 3.11 | PyO3 (abi3-py311) | | C | 11 | cbindgen | ## 从源码构建 -**前置条件:** Rust 1.89+,Python 3.10+(用于 Python 绑定) +**前置条件:** Rust 1.89+,Python 3.11+(用于 Python 绑定) ```bash git clone https://gitee.com/cq-lib/cqlib.git diff --git a/README.md b/README.md index 61968e94..b8db56a2 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE.txt) [![Rust](https://img.shields.io/badge/rust-1.89%2B-orange.svg)](https://www.rust-lang.org) -[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org) +[![Python](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org) [![C](https://img.shields.io/badge/c-11%2B-lightgrey.svg)](https://en.cppreference.com/w/c/11) [中文文档](README.CN.md) @@ -17,7 +17,7 @@ Cqlib is a high-performance quantum computing SDK that provides a unified foundation for building, optimizing, and executing quantum programs. Its core is written in Rust for maximum safety and speed, with first-class language bindings -for Python 3.10+ and C 11+. +for Python 3.11+ and C 11+. Designed from the ground up for both research and production use, Cqlib covers the full quantum computing workflow: from circuit construction and parameterization, through multi-level IR transformations, rule-based compilation and @@ -28,6 +28,8 @@ education, and integration into larger software stacks. Learn more at **[qc.zdxlz.com/cqlib](https://qc.zdxlz.com/cqlib)**. +**[Read the Whitepaper](docs/whitepaper/Cqlib.pdf)** — Cqlib's design philosophy, architecture, and technical details in one document. + ## Features - **Circuit Construction** — Intuitive APIs to build, compose, and parameterize quantum circuits @@ -140,12 +142,12 @@ int main(void) { | Language | Minimum Version | Binding Technology | |----------|-----------------|--------------------| | Rust | 1.89 | Native | -| Python | 3.10 | PyO3 (abi3-py310) | +| Python | 3.11 | PyO3 (abi3-py311) | | C | 11 | cbindgen | ## Building from Source -**Prerequisites:** Rust 1.89+, Python 3.10+ (for Python bindings) +**Prerequisites:** Rust 1.89+, Python 3.11+ (for Python bindings) ```bash git clone https://gitee.com/cq-lib/cqlib.git diff --git a/crates/binding-c/Cargo.toml b/crates/binding-c/Cargo.toml index 7c61cde5..ff6792b2 100644 --- a/crates/binding-c/Cargo.toml +++ b/crates/binding-c/Cargo.toml @@ -9,8 +9,9 @@ license.workspace = true crate-type = ["rlib", "staticlib", "cdylib"] [dependencies] -cqlib-core = { path = "../cqlib-core", version = "0.1.0-beta.1" } +cqlib-core = { path = "../cqlib-core", version = "0.1.0-beta.7" } libc = "0.2" +bitvec.workspace = true ndarray.workspace = true num-complex.workspace = true rustworkx-core.workspace = true diff --git a/crates/binding-c/README.md b/crates/binding-c/README.md index d5904499..a39a669e 100644 --- a/crates/binding-c/README.md +++ b/crates/binding-c/README.md @@ -121,4 +121,15 @@ gcc -I crates/binding-c/include \ -o test_circuit ./test_circuit # prints "binding-c circuit tests passed" -``` \ No newline at end of file +``` + +## Checked sparse algebra + +The new `fermionic_op_*`, `jordan_wigner_*`, and checked `hamiltonian_*` functions +expose fermionic products, excitation generators and sparse Pauli arithmetic. +They return an error code and deliver independent objects through output pointers; +errors leave outputs unchanged. Inputs are borrowed and coefficients are never +approximately pruned unless requested. See [Fermionic algebra](../../docs/api/en/c/3_qis/10_fermion.md) +and [Hamiltonian](../../docs/api/en/c/3_qis/7_hamiltonian.md). + +The staged SDK consumer tests include `test_qis_algebra.c` for both static and shared linking. diff --git a/crates/binding-c/src/circuit/parameter.rs b/crates/binding-c/src/circuit/parameter.rs index 2f9dfa0e..8ae00dfd 100644 --- a/crates/binding-c/src/circuit/parameter.rs +++ b/crates/binding-c/src/circuit/parameter.rs @@ -445,7 +445,8 @@ pub extern "C" fn param_replace( box_param(unsafe { (*a).inner.replace(symbol, replacement) }) } -/// Substitute several symbols in one call and simplify the result. +/// Simultaneously substitute symbols and simplify the result. Replacement +/// expressions are not substituted again; the original parameter is unchanged. /// `names` and `values` are parallel arrays of length `len`. Returns a new /// parameter, or NULL on NULL input, non-UTF-8 names or NULL elements. #[unsafe(no_mangle)] diff --git a/crates/binding-c/src/circuit/properties.rs b/crates/binding-c/src/circuit/properties.rs index 309c9fb8..992fd4a6 100644 --- a/crates/binding-c/src/circuit/properties.rs +++ b/crates/binding-c/src/circuit/properties.rs @@ -158,7 +158,9 @@ pub extern "C" fn circuit_to_matrix( } /// Compose another circuit into this one. `qubits_map` maps `other`'s qubits -/// to this circuit's qubits. NULL map uses identity mapping (merge by ID). +/// in insertion order to distinct qubits already in this circuit. +/// NULL or zero-length map uses identity mapping (merge by ID). +/// Errors leave this circuit unchanged. #[unsafe(no_mangle)] pub extern "C" fn circuit_compose( ptr: *mut CCircuit, diff --git a/crates/binding-c/src/compile/decompose.rs b/crates/binding-c/src/compile/decompose.rs index 143acea2..021cc5f8 100644 --- a/crates/binding-c/src/compile/decompose.rs +++ b/crates/binding-c/src/compile/decompose.rs @@ -29,7 +29,8 @@ use cqlib_core::compile::transform::decompose::unitary::{ synthesize_numeric_2q_unitary as core_synthesize_numeric_2q_unitary, }; use cqlib_core::compile::transform::decompose::{ - DecompositionRuleStats, McGateDecomposeConfig, UnitaryDecomposeConfig, + BlockZxzDecomposeOptions, DecompositionRuleStats, McGateDecomposeConfig, + UnitaryDecomposeConfig, decompose_block_zxz_with_options, decompose_mc_gates_with_rule_stats as core_decompose_mc_gates_with_rule_stats, decompose_unitaries_with_rule_stats as core_decompose_unitaries_with_rule_stats, expand_definitions as core_expand_definitions, @@ -71,6 +72,18 @@ pub const KAK_FACTOR_K1R: u8 = 1; pub const KAK_FACTOR_K2L: u8 = 2; pub const KAK_FACTOR_K2R: u8 = 3; +/// Hard side-length cap matching `MAX_UNITARY_QUBITS = 20` in `circuit_unitary`. +const BLOCK_ZXZ_MAX_DIM: usize = 1usize << 20; + +/// Absorb two outer controlled rotations' boundary CX gates per recursive layer. +pub const BLOCK_ZXZ_OPT_A1: u8 = 1; +/// Use a diagonal remainder between consecutive two-qubit leaves. +pub const BLOCK_ZXZ_OPT_A2: u8 = 2; +/// Permit A.2 on block-diagonal inputs when BLOCK_ZXZ_OPT_A2 is set. +pub const BLOCK_ZXZ_OPT_A2_FORCE: u8 = 4; +/// Default optimizations, with automatic block-diagonal handling. +pub const BLOCK_ZXZ_OPT_ALL: u8 = BLOCK_ZXZ_OPT_A1 | BLOCK_ZXZ_OPT_A2; + /// C snapshot of pass-local decomposition-rule cache statistics. #[repr(C)] pub struct CDecompositionRuleStats { @@ -91,8 +104,16 @@ pub struct CDecompositionRuleStats { pub struct CUnitaryDecomposeConfig { /// 1 recurses into control-flow bodies, 0 does not. pub recurse_control_flow: u8, + /// When nonzero, `block_zxz_options` selects the Block-ZXZ optimization + /// bitmask; when 0 (including zero-initialized structs), default + /// optimizations (`BLOCK_ZXZ_OPT_ALL`) are used. + pub has_block_zxz_options: u8, + /// Block-ZXZ optimization mask applied to three-or-more-qubit unitary gates + /// when `has_block_zxz_options != 0` (bitwise OR of `BLOCK_ZXZ_OPT_*`, or + /// 0 for unoptimized synthesis). + pub block_zxz_options: u8, /// Reserved padding to keep the struct layout stable. - pub _reserved: [u8; 7], + pub _reserved: [u8; 5], } /// C form of [`McGateDecomposeConfig`]. @@ -174,7 +195,9 @@ pub struct CTargetBasisLowerer { pub extern "C" fn decompose_unitary_config_default() -> CUnitaryDecomposeConfig { CUnitaryDecomposeConfig { recurse_control_flow: 1, - _reserved: [0; 7], + has_block_zxz_options: 1, + block_zxz_options: BLOCK_ZXZ_OPT_ALL, + _reserved: [0; 5], } } @@ -297,20 +320,32 @@ pub extern "C" fn decompose_unitaries_with_rule_stats( if circuit.is_null() { return std::ptr::null_mut(); } + let block_zxz_options = if config.has_block_zxz_options == 0 { + BlockZxzDecomposeOptions::default() + } else { + let Some(options) = block_zxz_options_from_mask(config.block_zxz_options) else { + return std::ptr::null_mut(); + }; + options + }; let config = UnitaryDecomposeConfig { two_qubit_target: Default::default(), recurse_control_flow: config.recurse_control_flow != 0, + block_zxz_options, }; - let circuit = unsafe { &(*circuit).inner }; - match core_decompose_unitaries_with_rule_stats(circuit, config) { - Ok((outcome, rule_stats)) => { - write_rule_stats(stats, &rule_stats); - Box::into_raw(Box::new(CCircuit { - inner: outcome.into_circuit(circuit), - })) + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + let circuit = unsafe { &(*circuit).inner }; + match core_decompose_unitaries_with_rule_stats(circuit, config) { + Ok((outcome, rule_stats)) => { + write_rule_stats(stats, &rule_stats); + Box::into_raw(Box::new(CCircuit { + inner: outcome.into_circuit(circuit), + })) + } + Err(_) => std::ptr::null_mut(), } - Err(_) => std::ptr::null_mut(), - } + })) + .unwrap_or(std::ptr::null_mut()) } /// Rewrites multi-controlled gates of `circuit` and returns the rebuilt @@ -1143,3 +1178,63 @@ pub extern "C" fn decompose_unitary_target_cost_of_fixed_operations( } CqlibError::Ok as i32 } + +fn block_zxz_options_from_mask(options: u8) -> Option { + if options & !(BLOCK_ZXZ_OPT_ALL | BLOCK_ZXZ_OPT_A2_FORCE) != 0 { + return None; + } + Some(BlockZxzDecomposeOptions { + opt_a1: options & BLOCK_ZXZ_OPT_A1 != 0, + opt_a2: options & BLOCK_ZXZ_OPT_A2 != 0, + opt_a2_force: options & BLOCK_ZXZ_OPT_A2_FORCE != 0, + }) +} + +/// Synthesizes a row-major unitary into an owned circuit including global phase. +/// `dim` must be a power of two in `[2, 2^20]`. `atol` must be finite and nonnegative. +/// Pass a bitwise OR of BLOCK_ZXZ_OPT_* flags, or zero to disable both. +/// Returns NULL on invalid input or synthesis failure. Release a successful +/// result with circuit_free. +/// +/// # Safety +/// A non-null matrix pointer with a valid shape must be aligned and point to +/// at least dim * dim initialized contiguous Complex64 values, each containing +/// two doubles (real, imaginary). The caller owns the input for this call. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn block_zxz_decompose( + matrix: *const Complex64, + dim: usize, + atol: f64, + options: u8, +) -> *mut CCircuit { + let Some(options) = block_zxz_options_from_mask(options) else { + return std::ptr::null_mut(); + }; + if matrix.is_null() + || !matrix.is_aligned() + || !(2..=BLOCK_ZXZ_MAX_DIM).contains(&dim) + || !dim.is_power_of_two() + || !atol.is_finite() + || atol < 0. + { + return std::ptr::null_mut(); + } + let Some(len) = dim.checked_mul(dim) else { + return std::ptr::null_mut(); + }; + if len > isize::MAX as usize / size_of::() { + return std::ptr::null_mut(); + } + std::panic::catch_unwind(|| { + // Shape, multiplication and byte extent have been checked before the first read. + let slice = unsafe { std::slice::from_raw_parts(matrix, len) }; + let matrix = ndarray::ArrayView2::from_shape((dim, dim), slice) + .ok()? + .to_owned(); + let inner = decompose_block_zxz_with_options(&matrix, atol, &options).ok()?; + Some(Box::into_raw(Box::new(CCircuit { inner }))) + }) + .ok() + .flatten() + .unwrap_or(std::ptr::null_mut()) +} diff --git a/crates/binding-c/src/error_mitigation/virtual_distillation.rs b/crates/binding-c/src/error_mitigation/virtual_distillation.rs index 78b42084..b40ceb61 100644 --- a/crates/binding-c/src/error_mitigation/virtual_distillation.rs +++ b/crates/binding-c/src/error_mitigation/virtual_distillation.rs @@ -45,10 +45,14 @@ pub extern "C" fn virtual_distillation_free(ptr: *mut CVirtualDistillation) { } } -/// Builds the copy-swap circuit used by the virtual distillation protocol. +/// Builds the copy-swap circuit used by the virtual distillation protocol +/// (a Hadamard-test circuit: one preparation per configured copy, a Hadamard +/// on a trailing ancilla qubit, and a ladder of ancilla-controlled SWAPs +/// between adjacent copies). /// -/// Returns an owned `CCircuit*` (free with `circuit_free`), or NULL -/// on error. +/// The circuit width is `copies * base_width + 1`, where the last qubit is +/// the ancilla. Returns an owned `CCircuit*` (free with `circuit_free`), or +/// NULL on error. #[unsafe(no_mangle)] pub extern "C" fn virtual_distillation_build_circuit( ptr: *const CVirtualDistillation, @@ -66,8 +70,10 @@ pub extern "C" fn virtual_distillation_build_circuit( /// Builds the copy-swap circuit from the base circuit (the C mirror of /// `VirtualDistillation::build_copy_swap_circuit`). /// -/// The circuit contains one preparation per configured copy plus pairwise -/// SWAPs against the first copy. Returns an owned `CCircuit*` (free with +/// The circuit contains one preparation per configured copy, a Hadamard +/// gate on a trailing ancilla qubit, and a ladder of ancilla-controlled +/// SWAPs (McGates) between adjacent copies. The width is +/// `copies * base_width + 1`. Returns an owned `CCircuit*` (free with /// `circuit_free`), or NULL on NULL input or a build failure. #[unsafe(no_mangle)] pub extern "C" fn virtual_distillation_build_copy_swap_circuit( @@ -116,8 +122,9 @@ pub extern "C" fn virtual_distillation_set_copies( /// mean and variance to the out pointers. /// /// The estimator receives the copy-swap circuit, a Hamiltonian expanded to -/// the full copy-swap width, and `shots`. Returns 0 on success or a negative -/// error code. +/// the full copy-swap width (the original Pauli terms on the first copy's +/// qubits, identity elsewhere, and an X on the ancilla qubit), and `shots`. +/// Returns 0 on success or a negative error code. #[unsafe(no_mangle)] pub extern "C" fn virtual_distillation_run_numerator_circuit( ptr: *const CVirtualDistillation, @@ -148,8 +155,9 @@ pub extern "C" fn virtual_distillation_run_numerator_circuit( /// Runs the denominator circuit through `estimator` and writes the estimated /// mean and variance to the out pointers. /// -/// The estimator receives the copy-swap circuit, no Hamiltonian (NULL), and -/// `shots`. Returns 0 on success or a negative error code. +/// The estimator receives the copy-swap circuit, the denominator Hamiltonian +/// (a single X term on the ancilla qubit, identity elsewhere), and `shots`. +/// Returns 0 on success or a negative error code. #[unsafe(no_mangle)] pub extern "C" fn virtual_distillation_run_denominator_circuit( ptr: *const CVirtualDistillation, @@ -171,7 +179,7 @@ pub extern "C" fn virtual_distillation_run_denominator_circuit( } CqlibError::Ok as i32 } - Err(_) => CqlibError::CircuitError as i32, + Err(err) => em_error_code(&err), } } diff --git a/crates/binding-c/src/qis/algebra.rs b/crates/binding-c/src/qis/algebra.rs new file mode 100644 index 00000000..cf20f8ec --- /dev/null +++ b/crates/binding-c/src/qis/algebra.rs @@ -0,0 +1,80 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Internal helpers for the checked algebra ABI. Legacy QIS error mapping is unchanged. + +use cqlib_core::qis::QisError; + +pub(crate) fn algebra_err_code(err: &QisError) -> i32 { + match err { + QisError::ModeOutOfBounds { .. } | QisError::IndexOutOfBounds { .. } => -2, + QisError::ModeMismatch { .. } + | QisError::QubitMismatch { .. } + | QisError::DimensionMismatch { .. } + | QisError::NonFiniteCoefficient { .. } + | QisError::InvalidOccupation { .. } + | QisError::InvalidParameterValue(_) + | QisError::NotHermitian => -8, + _ => super::qis_err_code(err), + } +} + +/// C callers must provide valid, aligned storage, live handles and exclusive +/// mutable outputs. NULL is allowed for empty arrays. Check the Rust slice size +/// bound before constructing a slice, including for malicious length values. +pub(crate) unsafe fn input_slice<'a, T>(ptr: *const T, len: usize) -> Result<&'a [T], i32> { + if len == 0 { + return Ok(&[]); + } + if ptr.is_null() { + return Err(-1); + } + if len > (isize::MAX as usize) / std::mem::size_of::() { + return Err(-8); + } + Ok(unsafe { std::slice::from_raw_parts(ptr, len) }) +} + +/// Only called after validating the output pointer. Write once on success. +pub(crate) unsafe fn write_result(out: *mut T, result: Result) -> i32 { + match result { + Ok(value) => { + unsafe { *out = value }; + 0 + } + Err(err) => algebra_err_code(&err), + } +} + +/// Check the same BitVec materialization limit used by core's checked algebra. +pub(crate) fn check_pauli_width(width: usize) -> Result<(), i32> { + if width > bitvec::slice::BitSlice::::MAX_BITS { + Err(-7) + } else { + Ok(()) + } +} + +/// Return 2^width only when the side length is representable. Do not truncate +/// usize widths to u32: zero sums may legally declare widths as large as usize::MAX. +pub(crate) fn dense_matrix_dim(width: usize) -> Option { + 1usize.checked_shl(u32::try_from(width).ok()?) +} + +/// Check element count and signed addressable byte size before allocation or +/// writing C buffers, matching Hamiltonian::to_matrix's allocation bounds. +pub(crate) fn dense_matrix_len(width: usize) -> Option { + let dim = dense_matrix_dim(width)?; + let len = dim.checked_mul(dim)?; + let bytes = len.checked_mul(std::mem::size_of::())?; + (bytes <= isize::MAX as usize).then_some(len) +} diff --git a/crates/binding-c/src/qis/density_matrix.rs b/crates/binding-c/src/qis/density_matrix.rs index e8119644..3075939d 100644 --- a/crates/binding-c/src/qis/density_matrix.rs +++ b/crates/binding-c/src/qis/density_matrix.rs @@ -94,28 +94,26 @@ fn apply_three( .map_or_else(|e| e, |_| 0) } +/// Returns a newly allocated simulator, or NULL if its dimension is +/// unrepresentable or its state allocation fails. #[unsafe(no_mangle)] pub extern "C" fn density_matrix_new(num_qubits: usize) -> *mut CDensityMatrix { - Box::into_raw(Box::new(CDensityMatrix { - inner: DensityMatrix::new(num_qubits), - })) + match DensityMatrix::try_new(num_qubits) { + Ok(inner) => Box::into_raw(Box::new(CDensityMatrix { inner })), + Err(_) => std::ptr::null_mut(), + } } /// Create a density matrix filled entirely with zeros. This is not a valid /// physical state (trace = 0); it is useful as an accumulator during /// operations like Kraus channel application. Returns NULL when the matrix -/// size overflows the addressable range. +/// size overflows the addressable range or state allocation fails. #[unsafe(no_mangle)] pub extern "C" fn density_matrix_zeros(num_qubits: usize) -> *mut CDensityMatrix { - let Some(bits) = num_qubits.checked_mul(2) else { - return std::ptr::null_mut(); - }; - if bits >= usize::BITS as usize { - return std::ptr::null_mut(); + match DensityMatrix::try_zeros(num_qubits) { + Ok(inner) => Box::into_raw(Box::new(CDensityMatrix { inner })), + Err(_) => std::ptr::null_mut(), } - Box::into_raw(Box::new(CDensityMatrix { - inner: DensityMatrix::zeros(num_qubits), - })) } #[unsafe(no_mangle)] @@ -818,11 +816,14 @@ pub extern "C" fn density_matrix_validate_physical(ptr: *const CDensityMatrix, t } /// Create the maximally mixed state I / 2^N of `num_qubits` qubits. +/// Returns a newly allocated simulator, or NULL if its dimension is +/// unrepresentable or its state allocation fails. #[unsafe(no_mangle)] pub extern "C" fn density_matrix_maximally_mixed(num_qubits: usize) -> *mut CDensityMatrix { - Box::into_raw(Box::new(CDensityMatrix { - inner: DensityMatrix::maximally_mixed(num_qubits), - })) + match DensityMatrix::try_maximally_mixed(num_qubits) { + Ok(inner) => Box::into_raw(Box::new(CDensityMatrix { inner })), + Err(_) => std::ptr::null_mut(), + } } /// Apply a standard gate identified by name (e.g. "H", "CX", "RZZ", "FSIM"). diff --git a/crates/binding-c/src/qis/density_matrix_noise.rs b/crates/binding-c/src/qis/density_matrix_noise.rs index b521a736..85d7be0b 100644 --- a/crates/binding-c/src/qis/density_matrix_noise.rs +++ b/crates/binding-c/src/qis/density_matrix_noise.rs @@ -124,15 +124,18 @@ fn apply_three( /// Create a new noisy simulator with `num_qubits` initialised to |0...0>. /// Pass NULL `noise_model` for an ideal (noise-free) simulation. +/// Returns a newly allocated simulator, or NULL if its dimension is +/// unrepresentable or its state allocation fails. #[unsafe(no_mangle)] pub extern "C" fn density_matrix_noise_new( num_qubits: usize, noise_model: *const CNoiseModel, ) -> *mut CDensityMatrixNoise { let noise = clone_noise_model(noise_model); - Box::into_raw(Box::new(CDensityMatrixNoise { - inner: DensityMatrixNoise::new(num_qubits, noise), - })) + match DensityMatrixNoise::try_new(num_qubits, noise) { + Ok(inner) => Box::into_raw(Box::new(CDensityMatrixNoise { inner })), + Err(_) => std::ptr::null_mut(), + } } /// Free a noisy simulator. NULL is allowed. @@ -679,6 +682,10 @@ pub extern "C" fn density_matrix_noise_probabilities_with_readout_len( /// Copy the probability distribution including readout errors configured in /// the noise model for `qubits` into `buffer`. Returns 0 on success. /// +/// `qubits` contains storage positions. For a circuit-bound state, noise is +/// looked up using the circuit ID at each position; unbound states use identity +/// IDs. The full output distribution retains storage order. +/// /// `qubits` may be NULL when `qubit_len` is 0, in which case no readout /// error is applied and the result matches `density_matrix_noise_probabilities`. #[unsafe(no_mangle)] diff --git a/crates/binding-c/src/qis/fermion.rs b/crates/binding-c/src/qis/fermion.rs new file mode 100644 index 00000000..b5784c2b --- /dev/null +++ b/crates/binding-c/src/qis/fermion.rs @@ -0,0 +1,599 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Checked fermionic algebra. All outputs and mutable inputs are unchanged on +//! failure. Object outputs are owned copies freed with `fermionic_op_free`; +//! inputs are borrowed. Multiplication applies the right operand first. + +use super::CHamiltonian; +use super::algebra::{algebra_err_code, check_pauli_width, input_slice, write_result}; +use cqlib_core::qis::fermion::mapping::{ + FermionToQubitMapper, JordanWignerMapper, OccupationStateMapper, +}; +use cqlib_core::qis::{FermionicLadder, FermionicOp}; +use libc::size_t; +use num_complex::Complex64; + +/// Opaque owned fermionic operator. No internal storage is exposed to C. +/// All checked functions return 0 on success and leave outputs unchanged on error. +/// Pass empty object output slots; results must be freed with the matching free +/// function. Caller storage must be live, aligned and large enough; output slots +/// must not overlap one another or handle internals. Inputs are borrowed. +/// Do not read a handle concurrently with mutation. Empty arrays permit NULL. +pub struct CFermionicOp { + pub inner: FermionicOp, +} + +/// Creation ladder tag. +pub const FERMIONIC_CREATE: u8 = 0; +/// Annihilation ladder tag. +pub const FERMIONIC_ANNIHILATE: u8 = 1; + +/// One ladder on a zero-based mode. Unknown kind tags return -8. +#[repr(C)] +#[derive(Clone, Copy)] +pub struct CFermionicLadder { + pub mode: size_t, + pub kind: u8, +} + +/// Borrowed ordered product and coefficient; the rightmost ladder acts first. +/// A NULL ladders pointer with len=0 denotes the identity product. +#[repr(C)] +pub struct CFermionicTerm { + pub ladders: *const CFermionicLadder, + pub len: size_t, + pub coefficient: Complex64, +} + +unsafe fn ladders(ptr: *const CFermionicLadder, len: size_t) -> Result, i32> { + unsafe { input_slice(ptr, len) }? + .iter() + .map(|ladder| match ladder.kind { + FERMIONIC_CREATE => Ok(FermionicLadder::Create(ladder.mode)), + FERMIONIC_ANNIHILATE => Ok(FermionicLadder::Annihilate(ladder.mode)), + _ => Err(-8), + }) + .collect() +} + +fn owned(inner: FermionicOp) -> *mut CFermionicOp { + Box::into_raw(Box::new(CFermionicOp { inner })) +} + +/// Release an owned operator. NULL is allowed. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_free(ptr: *mut CFermionicOp) { + if !ptr.is_null() { + unsafe { + drop(Box::from_raw(ptr)); + } + } +} + +/// Construct zero, retaining the declared width including zero modes. +/// Returns -1 for NULL out; writes an owned handle only on success. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_new(num_modes: size_t, out: *mut *mut CFermionicOp) -> i32 { + if out.is_null() { + return -1; + } + unsafe { + *out = owned(FermionicOp::new(num_modes)); + } + 0 +} + +/// Construct identity, retaining the declared width including zero modes. +/// Returns -1 for NULL out; writes an owned handle only on success. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_identity(num_modes: size_t, out: *mut *mut CFermionicOp) -> i32 { + if out.is_null() { + return -1; + } + unsafe { + *out = owned(FermionicOp::identity(num_modes)); + } + 0 +} + +/// Construct total particle number, retaining the declared width including zero modes. +/// Returns -1 for NULL out; writes an owned handle only on success. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_total_number(num_modes: size_t, out: *mut *mut CFermionicOp) -> i32 { + if out.is_null() { + return -1; + } + unsafe { + *out = owned(FermionicOp::total_number(num_modes)); + } + 0 +} + +/// Construct a mode creation operator. Returns -1 for NULL out, -2 for invalid mode. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_creation( + num_modes: size_t, + mode: size_t, + out: *mut *mut CFermionicOp, +) -> i32 { + if out.is_null() { + return -1; + } + unsafe { write_result(out, FermionicOp::creation(num_modes, mode).map(owned)) } +} + +/// Construct a mode annihilation operator. Returns -1 for NULL out, -2 for invalid mode. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_annihilation( + num_modes: size_t, + mode: size_t, + out: *mut *mut CFermionicOp, +) -> i32 { + if out.is_null() { + return -1; + } + unsafe { write_result(out, FermionicOp::annihilation(num_modes, mode).map(owned)) } +} + +/// Construct a mode number operator. Returns -1 for NULL out, -2 for invalid mode. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_number( + num_modes: size_t, + mode: size_t, + out: *mut *mut CFermionicOp, +) -> i32 { + if out.is_null() { + return -1; + } + unsafe { write_result(out, FermionicOp::number(num_modes, mode).map(owned)) } +} + +/// Construct a weighted ordered product. Empty product is identity; even +/// zero coefficients validate all modes. Returns -1 NULL, -2 mode, -8 tag/coefficient. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_from_term( + num_modes: size_t, + term: *const CFermionicLadder, + len: size_t, + coefficient: Complex64, + out: *mut *mut CFermionicOp, +) -> i32 { + if out.is_null() { + return -1; + } + let term = match unsafe { ladders(term, len) } { + Ok(v) => v, + Err(e) => return e, + }; + unsafe { + write_result( + out, + FermionicOp::from_term(num_modes, term, coefficient).map(owned), + ) + } +} + +/// Construct a sum of borrowed terms, merging identical products and removing +/// only exact zeros. NULL terms with len=0 creates zero. No input is consumed. +/// Returns -1 NULL, -2 invalid mode, -8 invalid tag/coefficient or length. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_from_terms( + num_modes: size_t, + terms: *const CFermionicTerm, + len: size_t, + out: *mut *mut CFermionicOp, +) -> i32 { + if out.is_null() { + return -1; + } + let terms = match unsafe { input_slice(terms, len) } { + Ok(v) => v, + Err(e) => return e, + }; + let mut result = FermionicOp::new(num_modes); + for term in terms { + let product = match unsafe { ladders(term.ladders, term.len) } { + Ok(v) => v, + Err(e) => return e, + }; + if let Err(err) = result.add_term(product, term.coefficient) { + return algebra_err_code(&err); + } + } + unsafe { + *out = owned(result); + } + 0 +} + +/// Add an ordered term atomically. Inputs are copied. Empty product is identity. +/// Returns -1 NULL, -2 mode, -8 tag/nonfinite coefficient (including merge overflow). +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_add_term( + ptr: *mut CFermionicOp, + term: *const CFermionicLadder, + len: size_t, + coefficient: Complex64, +) -> i32 { + if ptr.is_null() { + return -1; + } + let term = match unsafe { ladders(term, len) } { + Ok(v) => v, + Err(e) => return e, + }; + match unsafe { &mut (*ptr).inner }.add_term(term, coefficient) { + Ok(()) => 0, + Err(err) => algebra_err_code(&err), + } +} + +/// Construct G=i(T-T†). Target creators retain input order; source annihilators +/// use reverse input order. No sorting or factorial. Returns -1 NULL, -2 mode, +/// -8 empty/unequal lists, duplicates or overlap. Inputs are borrowed. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_excitation_generator( + num_modes: size_t, + sources: *const size_t, + sources_len: size_t, + targets: *const size_t, + targets_len: size_t, + out: *mut *mut CFermionicOp, +) -> i32 { + if out.is_null() { + return -1; + } + let sources = match unsafe { input_slice(sources, sources_len) } { + Ok(v) => v, + Err(e) => return e, + }; + let targets = match unsafe { input_slice(targets, targets_len) } { + Ok(v) => v, + Err(e) => return e, + }; + unsafe { + write_result( + out, + FermionicOp::excitation_generator(num_modes, sources, targets).map(owned), + ) + } +} + +/// Read declared mode count. Returns -1 for NULL input or output. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_num_modes(ptr: *const CFermionicOp, out: *mut size_t) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { + *out = inner.num_modes(); + } + 0 +} + +/// Read stored product count. Returns -1 for NULL input or output. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_num_terms(ptr: *const CFermionicOp, out: *mut size_t) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { + *out = inner.num_terms(); + } + 0 +} + +/// Read structural zero (0/1); use equiv for algebraic zero. Returns -1 for NULL input or output. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_is_zero(ptr: *const CFermionicOp, out: *mut u8) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { + *out = u8::from(inner.is_zero()); + } + 0 +} + +/// Return an owned independent copy. +/// Returns -1 for NULL input or output. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_copy(ptr: *const CFermionicOp, out: *mut *mut CFermionicOp) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { write_result(out, Ok(owned(inner.clone()))) } +} + +/// Return an owned conjugate transpose, reversing products and exchanging ladder kinds. +/// Returns -1 for NULL input or output. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_adjoint( + ptr: *const CFermionicOp, + out: *mut *mut CFermionicOp, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { write_result(out, Ok(owned(inner.adjoint()))) } +} + +/// Return an owned normal-ordered expansion with contraction terms and fermionic signs. +/// Returns -1 NULL; normal ordering may return -8 on coefficient overflow. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_normal_order( + ptr: *const CFermionicOp, + out: *mut *mut CFermionicOp, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { write_result(out, inner.normal_order().map(owned)) } +} + +/// Checked add, returning an independent operator without normal ordering. +/// Returns -1 NULL, -8 mode mismatch/nonfinite arithmetic. Right operand acts first in mul. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_add( + left: *const CFermionicOp, + right: *const CFermionicOp, + out: *mut *mut CFermionicOp, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*left).inner.try_add(&(*right).inner).map(owned)) } +} + +/// Checked sub, returning an independent operator without normal ordering. +/// Returns -1 NULL, -8 mode mismatch/nonfinite arithmetic. Right operand acts first in mul. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_sub( + left: *const CFermionicOp, + right: *const CFermionicOp, + out: *mut *mut CFermionicOp, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*left).inner.try_sub(&(*right).inner).map(owned)) } +} + +/// Checked mul, returning an independent operator without normal ordering. +/// Returns -1 NULL, -8 mode mismatch/nonfinite arithmetic. Right operand acts first in mul. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_mul( + left: *const CFermionicOp, + right: *const CFermionicOp, + out: *mut *mut CFermionicOp, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*left).inner.try_mul(&(*right).inner).map(owned)) } +} + +/// Return a scaled copy. Returns -1 NULL, -8 nonfinite factor or result. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_scaled( + ptr: *const CFermionicOp, + factor: Complex64, + out: *mut *mut CFermionicOp, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*ptr).inner.scaled(factor).map(owned)) } +} + +/// Remove coefficients with magnitude <= atol in place. Returns -1 NULL, +/// -8 for negative/nonfinite atol. Failure leaves the operator unchanged. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_chop(ptr: *mut CFermionicOp, atol: f64) -> i32 { + if ptr.is_null() { + return -1; + } + match unsafe { &mut (*ptr).inner }.chop(atol) { + Ok(()) => 0, + Err(e) => algebra_err_code(&e), + } +} + +/// Structural equality including mode count; writes 0 or 1. Returns -1 NULL. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_equals( + left: *const CFermionicOp, + right: *const CFermionicOp, + out: *mut u8, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { + *out = u8::from((*left).inner == (*right).inner); + } + 0 +} + +/// Algebraic equivalence after normal ordering; writes 0 or 1. Returns -1 NULL, +/// -8 mode mismatch, invalid atol or arithmetic overflow. atol=0 is exact. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_equiv( + left: *const CFermionicOp, + right: *const CFermionicOp, + atol: f64, + out: *mut u8, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { + write_result( + out, + (*left).inner.equiv(&(*right).inner, atol).map(u8::from), + ) + } +} + +/// Algebraic Hermiticity test; writes 0 or 1. Returns -1 NULL, -8 invalid atol/overflow. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_is_hermitian( + ptr: *const CFermionicOp, + atol: f64, + out: *mut u8, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*ptr).inner.is_hermitian(atol).map(u8::from)) } +} + +/// Read one stored product's length in deterministic structural order. +/// Returns -1 NULL, -2 invalid term index. No internal storage is borrowed. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_term_len( + ptr: *const CFermionicOp, + index: size_t, + out: *mut size_t, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let Some((term, _)) = (unsafe { &(*ptr).inner }).terms().nth(index) else { + return -2; + }; + unsafe { + *out = term.len(); + } + 0 +} + +/// Copy a term's ladders and coefficient in deterministic structural order. +/// Returns -1 NULL required pointer, -2 index, -8 insufficient capacity. +/// NULL buffer is allowed for an empty product. Writes no partial output on error. +#[unsafe(no_mangle)] +pub extern "C" fn fermionic_op_get_term( + ptr: *const CFermionicOp, + index: size_t, + buffer: *mut CFermionicLadder, + capacity: size_t, + out_coefficient: *mut Complex64, +) -> i32 { + if ptr.is_null() || out_coefficient.is_null() { + return -1; + } + let Some((term, coefficient)) = (unsafe { &(*ptr).inner }).terms().nth(index) else { + return -2; + }; + if capacity < term.len() { + return -8; + } + if !term.is_empty() && buffer.is_null() { + return -1; + } + for (i, ladder) in term.iter().enumerate() { + let kind = match ladder { + FermionicLadder::Create(_) => FERMIONIC_CREATE, + FermionicLadder::Annihilate(_) => FERMIONIC_ANNIHILATE, + }; + unsafe { + *buffer.add(i) = CFermionicLadder { + mode: ladder.mode(), + kind, + }; + } + } + unsafe { + *out_coefficient = coefficient; + } + 0 +} + +/// Map a borrowed operator to an owned CHamiltonian; free with hamiltonian_free. +/// Non-Hermitian inputs are valid. Mode p maps to qubit p, with Z on lower modes. +/// Returns -1 NULL, -7 unrepresentable width, -8 nonfinite arithmetic. +#[unsafe(no_mangle)] +pub extern "C" fn jordan_wigner_map_operator( + ptr: *const CFermionicOp, + out: *mut *mut CHamiltonian, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + // Zero operators need no bit vectors. All other inputs materialize a Pauli + // identity before mapping; guard that allocation like checked core algebra. + if !inner.is_zero() + && let Err(e) = check_pauli_width(inner.num_modes()) + { + return e; + } + unsafe { + write_result( + out, + JordanWignerMapper + .map_operator(inner) + .map(|inner| Box::into_raw(Box::new(CHamiltonian { inner }))), + ) + } +} + +/// Jordan-Wigner uses one qubit per mode. Returns -1 for NULL out. +#[unsafe(no_mangle)] +pub extern "C" fn jordan_wigner_num_qubits(num_modes: size_t, out: *mut size_t) -> i32 { + if out.is_null() { + return -1; + } + unsafe { + *out = JordanWignerMapper.num_qubits(num_modes); + } + 0 +} + +/// Encode occupations as 0/1 bytes: bits[p] addresses qubit p (LSB is qubit 0). +/// Empty input is vacuum. Returns -1 NULL required buffer, -8 invalid occupations, +/// length or insufficient capacity. Buffers may overlap: input is read before output. +#[unsafe(no_mangle)] +pub extern "C" fn jordan_wigner_map_occupation( + occupation: *const u8, + len: size_t, + out_bits: *mut u8, + capacity: size_t, +) -> i32 { + if len > 0 && (occupation.is_null() || out_bits.is_null()) { + return -1; + } + if capacity < len { + return -8; + } + let occupation = match unsafe { input_slice(occupation, len) } { + Ok(v) => v, + Err(e) => return e, + }; + let bits = match JordanWignerMapper.map_occupation(occupation) { + Ok(v) => v, + Err(e) => return algebra_err_code(&e), + }; + for (i, bit) in bits.into_iter().enumerate() { + unsafe { + *out_bits.add(i) = u8::from(bit); + } + } + 0 +} diff --git a/crates/binding-c/src/qis/hamiltonian.rs b/crates/binding-c/src/qis/hamiltonian.rs index 25a18be3..dec76e59 100644 --- a/crates/binding-c/src/qis/hamiltonian.rs +++ b/crates/binding-c/src/qis/hamiltonian.rs @@ -14,6 +14,7 @@ use crate::circuit::CCircuit; use crate::error::CqlibError; +use crate::qis::algebra::{dense_matrix_dim, dense_matrix_len}; use crate::qis::{CHamiltonian, CPauliString, CStatevector, qis_err_code}; use cqlib_core::qis::evolution::TrotterMode; use cqlib_core::qis::{Hamiltonian, Observable}; @@ -141,19 +142,22 @@ pub extern "C" fn hamiltonian_scale(ptr: *mut CHamiltonian, factor_re: f64, fact 0 } -/// Return the side length of the dense matrix (`2^N`), or 0 for NULL. +/// Return the side length of the dense matrix (`2^N`), or 0 for NULL or +/// an unrepresentable side length. A representable side does not guarantee +/// that the complete dense matrix can be allocated. #[unsafe(no_mangle)] pub extern "C" fn hamiltonian_to_matrix_len(ptr: *const CHamiltonian) -> usize { if ptr.is_null() { return 0; } - 1usize << unsafe { (*ptr).inner.num_qubits } + dense_matrix_dim(unsafe { (*ptr).inner.num_qubits }).unwrap_or(0) } /// Copy the dense `2^N x 2^N` matrix into `buffer` (row-major, /// `Complex64` values). `len` must equal /// `hamiltonian_to_matrix_len(ptr) * hamiltonian_to_matrix_len(ptr)`. -/// Returns 0 on success, or a negative error code. +/// Returns 0 on success, -7 for unrepresentable dense allocation size or +/// allocation failure, -8 for an incorrect buffer length. Errors leave the buffer unchanged. #[unsafe(no_mangle)] pub extern "C" fn hamiltonian_to_matrix( ptr: *const CHamiltonian, @@ -164,6 +168,12 @@ pub extern "C" fn hamiltonian_to_matrix( return CqlibError::NullPtr as i32; } let wrapper = unsafe { &*ptr }; + let Some(expected_len) = dense_matrix_len(wrapper.inner.num_qubits) else { + return CqlibError::SimulationError as i32; + }; + if len != expected_len { + return CqlibError::InvalidParam as i32; + } let matrix = match wrapper.inner.to_matrix() { Ok(matrix) => matrix, Err(err) => return qis_err_code(&err), @@ -171,9 +181,9 @@ pub extern "C" fn hamiltonian_to_matrix( if matrix.len() != len { return CqlibError::InvalidParam as i32; } - let flat: Vec = matrix.iter().cloned().collect(); + // Checked core conversion returns a contiguous row-major matrix. unsafe { - std::ptr::copy_nonoverlapping(flat.as_ptr(), buffer, len); + std::ptr::copy_nonoverlapping(matrix.as_ptr(), buffer, len); } 0 } diff --git a/crates/binding-c/src/qis/hamiltonian_algebra.rs b/crates/binding-c/src/qis/hamiltonian_algebra.rs new file mode 100644 index 00000000..9a1752f4 --- /dev/null +++ b/crates/binding-c/src/qis/hamiltonian_algebra.rs @@ -0,0 +1,302 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Checked Pauli sums. Inputs are borrowed and outputs owned; errors do not +//! overwrite outputs. Only exact zeros are removed unless chop is requested. + +use super::algebra::{algebra_err_code, check_pauli_width, input_slice, write_result}; +use super::{CHamiltonian, CPauliString}; +use cqlib_core::qis::Hamiltonian; +use libc::size_t; +use num_complex::Complex64; + +/// Borrowed Pauli term for checked batch construction. Pauli handles are copied. +#[repr(C)] +pub struct CHamiltonianTerm { + pub pauli: *const CPauliString, + pub coefficient: Complex64, +} + +fn owned(inner: Hamiltonian) -> *mut CHamiltonian { + Box::into_raw(Box::new(CHamiltonian { inner })) +} + +/// Construct identity, including scalar one on zero qubits. Returns -1 NULL out, +/// -7 width beyond the BitVec representation limit. Free with hamiltonian_free. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_identity(num_qubits: size_t, out: *mut *mut CHamiltonian) -> i32 { + if out.is_null() { + return -1; + } + if let Err(e) = check_pauli_width(num_qubits) { + return e; + } + unsafe { + *out = owned(Hamiltonian::identity(num_qubits)); + } + 0 +} + +/// Construct a checked, phase-normalized sum, merging duplicate Paulis. +/// Empty input retains num_qubits, including zero. Inputs are copied. +/// Returns -1 NULL term/out/Pauli, -8 width mismatch, nonfinite coefficient or overflow. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_from_terms( + num_qubits: size_t, + terms: *const CHamiltonianTerm, + len: size_t, + out: *mut *mut CHamiltonian, +) -> i32 { + if out.is_null() { + return -1; + } + let terms = match unsafe { input_slice(terms, len) } { + Ok(v) => v, + Err(e) => return e, + }; + let mut copied = Vec::with_capacity(terms.len()); + for term in terms { + if term.pauli.is_null() { + return -1; + } + copied.push((unsafe { &(*term.pauli).inner }.clone(), term.coefficient)); + } + unsafe { write_result(out, Hamiltonian::from_terms(num_qubits, copied).map(owned)) } +} + +/// Return an owned independent structural copy. +/// Free with hamiltonian_free. Returns -1 NULL; copies storage without normalization. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_copy(ptr: *const CHamiltonian, out: *mut *mut CHamiltonian) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { write_result(out, Ok(owned(inner.clone()))) } +} + +/// Return an owned validated copy with phases absorbed and exact zeros removed. +/// Free with hamiltonian_free. Returns -1 NULL, -8 invalid input or merge overflow. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_normalized( + ptr: *const CHamiltonian, + out: *mut *mut CHamiltonian, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { write_result(out, inner.normalized().map(owned)) } +} + +/// Return an owned normalized Hermitian copy; imaginary residuals <=1e-10 are projected to zero. +/// Free with hamiltonian_free. Returns -1 NULL, -8 invalid input or non-Hermitian projection. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_normalized_hermitian( + ptr: *const CHamiltonian, + out: *mut *mut CHamiltonian, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { write_result(out, inner.normalized_hermitian().map(owned)) } +} + +/// Return an owned conjugate transpose after absorbing Pauli phases. +/// Free with hamiltonian_free. Returns -1 NULL, -8 invalid input or merge overflow. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_adjoint( + ptr: *const CHamiltonian, + out: *mut *mut CHamiltonian, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let inner = unsafe { &(*ptr).inner }; + unsafe { write_result(out, inner.adjoint().map(owned)) } +} + +/// Checked add, retaining every nonzero coefficient. +/// Returns an owned result. -1 NULL, -8 width mismatch/nonfinite arithmetic, +/// -7 unrepresentable tensor width. No input is modified. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_add( + left: *const CHamiltonian, + right: *const CHamiltonian, + out: *mut *mut CHamiltonian, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*left).inner.try_add(&(*right).inner).map(owned)) } +} + +/// Checked sub, retaining every nonzero coefficient. +/// Returns an owned result. -1 NULL, -8 width mismatch/nonfinite arithmetic, +/// -7 unrepresentable tensor width. No input is modified. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_sub( + left: *const CHamiltonian, + right: *const CHamiltonian, + out: *mut *mut CHamiltonian, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*left).inner.try_sub(&(*right).inner).map(owned)) } +} + +/// Checked mul, retaining every nonzero coefficient. Right operand acts first. +/// Returns an owned result. -1 NULL, -8 width mismatch/nonfinite arithmetic, +/// -7 unrepresentable tensor width. No input is modified. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_mul( + left: *const CHamiltonian, + right: *const CHamiltonian, + out: *mut *mut CHamiltonian, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*left).inner.try_mul(&(*right).inner).map(owned)) } +} + +/// Checked tensor, retaining every nonzero coefficient. Right operand occupies low qubits, left high qubits. +/// Returns an owned result. -1 NULL, -8 width mismatch/nonfinite arithmetic, +/// -7 unrepresentable tensor width. No input is modified. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_tensor( + left: *const CHamiltonian, + right: *const CHamiltonian, + out: *mut *mut CHamiltonian, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*left).inner.tensor(&(*right).inner).map(owned)) } +} + +/// Return a checked scaled copy. Returns -1 NULL, -8 nonfinite input/factor/result. +/// Unlike legacy hamiltonian_scale, all stored coefficients are validated. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_scaled( + ptr: *const CHamiltonian, + factor: Complex64, + out: *mut *mut CHamiltonian, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*ptr).inner.scaled(factor).map(owned)) } +} + +/// Embed mapping[source]=destination. Destinations must be distinct and in range; +/// unused target qubits are identity. Not a fermionic mode permutation. +/// Returns -1 NULL, -8 invalid mapping/input, -7 unrepresentable target width. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_remap_qubits( + ptr: *const CHamiltonian, + mapping: *const size_t, + len: size_t, + target_width: size_t, + out: *mut *mut CHamiltonian, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + let mapping = match unsafe { input_slice(mapping, len) } { + Ok(v) => v, + Err(e) => return e, + }; + unsafe { + write_result( + out, + (*ptr).inner.remap_qubits(mapping, target_width).map(owned), + ) + } +} + +/// Normalize then remove coefficients with magnitude <=atol in place. +/// Returns -1 NULL, -8 negative/nonfinite atol or invalid input. Failure is atomic. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_chop(ptr: *mut CHamiltonian, atol: f64) -> i32 { + if ptr.is_null() { + return -1; + } + match unsafe { &mut (*ptr).inner }.chop(atol) { + Ok(()) => 0, + Err(e) => algebra_err_code(&e), + } +} + +/// Compare normalized coefficient differences to atol; writes 0 or 1. +/// Returns -1 NULL, -8 invalid atol, width mismatch or nonfinite arithmetic. +/// atol is a coefficient tolerance, not an operator norm bound. atol=0 is exact. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_equiv( + left: *const CHamiltonian, + right: *const CHamiltonian, + atol: f64, + out: *mut u8, +) -> i32 { + if left.is_null() || right.is_null() || out.is_null() { + return -1; + } + unsafe { + write_result( + out, + (*left).inner.equiv(&(*right).inner, atol).map(u8::from), + ) + } +} + +/// Test equivalence with the adjoint; writes 0 or 1. For normalized coefficients +/// this bounds twice the imaginary magnitude. Does not project coefficients. +/// Returns -1 NULL, -8 invalid atol/input or arithmetic overflow. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_is_hermitian( + ptr: *const CHamiltonian, + atol: f64, + out: *mut u8, +) -> i32 { + if ptr.is_null() || out.is_null() { + return -1; + } + unsafe { write_result(out, (*ptr).inner.is_hermitian(atol).map(u8::from)) } +} + +/// Read one stored term by index, returning an independent Pauli handle and +/// coefficient. Free the Pauli with pauli_string_free; it may have zero width. +/// Both outputs are unchanged on error. Returns -1 NULL, -2 invalid index. +#[unsafe(no_mangle)] +pub extern "C" fn hamiltonian_get_term( + ptr: *const CHamiltonian, + index: size_t, + out_pauli: *mut *mut CPauliString, + out_coefficient: *mut Complex64, +) -> i32 { + if ptr.is_null() || out_pauli.is_null() || out_coefficient.is_null() { + return -1; + } + let Some((pauli, coefficient)) = (unsafe { &(*ptr).inner }).terms.get(index) else { + return -2; + }; + let copied = Box::into_raw(Box::new(CPauliString { + inner: pauli.clone(), + })); + unsafe { + *out_pauli = copied; + *out_coefficient = *coefficient; + } + 0 +} diff --git a/crates/binding-c/src/qis/mod.rs b/crates/binding-c/src/qis/mod.rs index 8628c2fc..ebd47e89 100644 --- a/crates/binding-c/src/qis/mod.rs +++ b/crates/binding-c/src/qis/mod.rs @@ -14,10 +14,13 @@ #![allow(clippy::not_unsafe_ptr_arg_deref)] +mod algebra; pub mod density_matrix; pub mod density_matrix_noise; pub mod entropy; +pub mod fermion; pub mod hamiltonian; +pub mod hamiltonian_algebra; pub mod measurement; pub mod metrics; pub mod pauli; @@ -103,7 +106,9 @@ pub(crate) fn qis_err_code(err: &cqlib_core::qis::QisError) -> i32 { pub use density_matrix::*; pub use density_matrix_noise::*; pub use entropy::*; +pub use fermion::*; pub use hamiltonian::*; +pub use hamiltonian_algebra::*; pub use measurement::*; pub use metrics::*; pub use pauli::*; diff --git a/crates/binding-c/src/qis/pauli.rs b/crates/binding-c/src/qis/pauli.rs index 7a88e9a7..305dde8e 100644 --- a/crates/binding-c/src/qis/pauli.rs +++ b/crates/binding-c/src/qis/pauli.rs @@ -13,8 +13,9 @@ //! C ABI for `PauliString` and single-qubit Pauli operators. use crate::error::CqlibError; +use crate::qis::algebra::{dense_matrix_dim, dense_matrix_len}; use crate::qis::{CPauliString, qis_err_code}; -use cqlib_core::qis::{Pauli, PauliString}; +use cqlib_core::qis::{Hamiltonian, Pauli, PauliString}; use std::collections::HashMap; use std::ffi::{CStr, CString}; use std::os::raw::c_char; @@ -184,22 +185,22 @@ pub extern "C" fn pauli_string_to_string(ptr: *const CPauliString) -> *mut c_cha } } -/// Flatten the dense matrix representation into `buffer`. -/// -/// The matrix has dimensions `2^N × 2^N` and is stored in row-major order -/// as `Complex64` values. Use `pauli_string_matrix_len` first to obtain -/// the side length (`2^N`). Returns 0 on success. +/// Return the side length (`2^N`) of the row-major dense matrix, or 0 for +/// NULL or an unrepresentable side length. A representable side does not +/// guarantee that the complete dense matrix can be allocated. #[unsafe(no_mangle)] pub extern "C" fn pauli_string_matrix_len(ptr: *const CPauliString) -> usize { if ptr.is_null() { return 0; } let wrapper = unsafe { &*ptr }; - 1usize << wrapper.inner.num_qubits + dense_matrix_dim(wrapper.inner.num_qubits).unwrap_or(0) } /// Copy the dense matrix into `buffer` (row-major, `Complex64` values). /// `len` must equal `pauli_string_matrix_len(ptr) * pauli_string_matrix_len(ptr)`. +/// Returns -7 for unrepresentable dense allocation size or allocation failure, +/// -8 for an incorrect buffer length. Errors leave the buffer unchanged. #[unsafe(no_mangle)] pub extern "C" fn pauli_string_matrix( ptr: *const CPauliString, @@ -210,14 +211,19 @@ pub extern "C" fn pauli_string_matrix( return CqlibError::NullPtr as i32; } let wrapper = unsafe { &*ptr }; - let matrix = wrapper.inner.to_matrix(); - let dim = 1usize << wrapper.inner.num_qubits; - if matrix.len() != len || len != dim * dim { + let Some(expected_len) = dense_matrix_len(wrapper.inner.num_qubits) else { + return CqlibError::SimulationError as i32; + }; + if len != expected_len { return CqlibError::InvalidParam as i32; } - let flat: Vec = matrix.iter().cloned().collect(); + let matrix = match Hamiltonian::from_pauli(wrapper.inner.clone()).to_matrix() { + Ok(matrix) => matrix, + Err(err) => return qis_err_code(&err), + }; + // Checked core conversion returns a contiguous row-major matrix. unsafe { - std::ptr::copy_nonoverlapping(flat.as_ptr(), buffer, len); + std::ptr::copy_nonoverlapping(matrix.as_ptr(), buffer, len); } 0 } diff --git a/crates/binding-c/src/qis/statevector.rs b/crates/binding-c/src/qis/statevector.rs index cdb492ca..de03f952 100644 --- a/crates/binding-c/src/qis/statevector.rs +++ b/crates/binding-c/src/qis/statevector.rs @@ -97,11 +97,14 @@ fn apply_three( } /// Create a new statevector with `num_qubits` initialised to |0...0>. +/// Returns a newly allocated simulator, or NULL if its dimension is +/// unrepresentable or its state allocation fails. #[unsafe(no_mangle)] pub extern "C" fn statevector_new(num_qubits: usize) -> *mut CStatevector { - Box::into_raw(Box::new(CStatevector { - inner: Statevector::new(num_qubits), - })) + match Statevector::try_new(num_qubits) { + Ok(inner) => Box::into_raw(Box::new(CStatevector { inner })), + Err(_) => std::ptr::null_mut(), + } } /// Free a statevector. NULL is allowed. diff --git a/crates/binding-c/tests/circuit_test.rs b/crates/binding-c/tests/circuit_test.rs index 1490794c..26b98384 100644 --- a/crates/binding-c/tests/circuit_test.rs +++ b/crates/binding-c/tests/circuit_test.rs @@ -289,6 +289,52 @@ fn compose_and_add_qubits() { circuit_free(circuit); } +#[test] +fn compose_rejects_duplicate_targets_without_mutation() { + for width in [1, 2] { + let circuit = circuit_new(width); + assert_eq!(circuit_h(circuit, 0), 0); + let len = circuit_to_matrix_len(circuit, std::ptr::null(), 0); + let mut before = vec![0.0; len * 2]; + assert_eq!( + circuit_to_matrix( + circuit, + std::ptr::null(), + 0, + before.as_mut_ptr(), + before.len() + ), + len + ); + let other = circuit_new(2); + assert_eq!(circuit_cx(other, 0, 1), 0); + let mapping = [0, 0]; + + assert_eq!( + circuit_compose(circuit, other, mapping.as_ptr(), mapping.len()), + -3 + ); + + assert_eq!(circuit_num_qubits(circuit), width); + assert_eq!(circuit_num_operations(circuit), 1); + assert_eq!(circuit_num_operations(other), 1); + let mut after = vec![0.0; len * 2]; + assert_eq!( + circuit_to_matrix( + circuit, + std::ptr::null(), + 0, + after.as_mut_ptr(), + after.len() + ), + len + ); + assert_eq!(after, before); + circuit_free(other); + circuit_free(circuit); + } +} + #[test] fn global_phase_operations() { let circuit = circuit_new(1); diff --git a/crates/binding-c/tests/compile_pass2_test.rs b/crates/binding-c/tests/compile_pass2_test.rs index 30edee93..1f2c4ffa 100644 --- a/crates/binding-c/tests/compile_pass2_test.rs +++ b/crates/binding-c/tests/compile_pass2_test.rs @@ -22,6 +22,124 @@ fn zeroed() -> T { unsafe { std::mem::zeroed() } } +#[test] +fn test_weyl_boundary_kak_synthesis_and_unitary_decomposition() { + use binding_c::circuit::{circuit_to_matrix, circuit_to_matrix_len}; + use cqlib_core::circuit::StandardGate; + use ndarray::{Array2, linalg::kron}; + // Reported boundary unitary in the row-major order accepted by the C ABI. + let flat = [ + Complex64::new(-0.14755155196621783, 0.08535345227001921), + Complex64::new(-0.015112015359785388, -0.026124324914469213), + Complex64::new(-4.3021142204224816e-16, 0.06601980439593577), + Complex64::new(-0.9826870609532827, 2.7755575615628914e-16), + Complex64::new(-0.006212290419590961, -0.010739262071974568), + Complex64::new(-0.3589338503302527, 0.2076307761864266), + Complex64::new(0.9070757873156866, -5.412337245047638e-16), + Complex64::new(-6.245004513516506e-16, -0.07152302867497204), + Complex64::new(-0.9706933646378622, 2.7755575615628914e-17), + Complex64::new(2.6020852139652106e-18, -0.15594957493615416), + Complex64::new(0.03569705171577718, -0.061709927849413246), + Complex64::new(0.1457506851638859, 0.08431171332109447), + Complex64::new(7.112366251504909e-17, -0.16894909068671718), + Complex64::new(-0.8960049266516804, -3.608224830031759e-16), + Complex64::new(-0.35455306241796475, -0.20509664240745978), + Complex64::new(-0.014674445936026376, 0.02536789332498595), + ]; + let matrix = Array2::from_shape_vec((4, 4), flat.to_vec()).unwrap(); + let kak = kak_decompose(flat.as_ptr()); + assert!(!kak.is_null()); + let (mut a, mut b, mut c) = (0.0, 0.0, 0.0); + assert_eq!( + kak_decomposition_coordinates(kak, &mut a, &mut b, &mut c), + 0 + ); + assert_eq!(a, std::f64::consts::FRAC_PI_4); + assert!(c > 0.0); + let mut local = Vec::new(); + for tag in [ + KAK_FACTOR_K1L, + KAK_FACTOR_K1R, + KAK_FACTOR_K2L, + KAK_FACTOR_K2R, + ] { + let mut values = vec![Complex64::new(0.0, 0.0); 4]; + assert_eq!( + kak_decomposition_local_factor(kak, tag, values.as_mut_ptr()), + 0 + ); + local.push(Array2::from_shape_vec((2, 2), values).unwrap()); + } + let rxx = StandardGate::RXX.matrix(&[-2.0 * a]).unwrap().into_owned(); + let ryy = StandardGate::RYY.matrix(&[-2.0 * b]).unwrap().into_owned(); + let rzz = StandardGate::RZZ.matrix(&[-2.0 * c]).unwrap().into_owned(); + let core = rxx.dot(&ryy).dot(&rzz); + let phase = Complex64::from_polar(1.0, kak_decomposition_global_phase(kak)); + let reconstructed = kron(&local[0], &local[1]) + .dot(&core) + .dot(&kron(&local[2], &local[3])); + assert!( + reconstructed + .iter() + .zip(matrix.iter()) + .all(|(actual, expected)| (phase * actual - expected).norm() < 1e-12) + ); + kak_decomposition_free(kak); + + for basis in [ + TWO_QUBIT_BASIS_CX, + TWO_QUBIT_BASIS_CY, + TWO_QUBIT_BASIS_CZ, + TWO_QUBIT_BASIS_RZZ, + TWO_QUBIT_BASIS_PAULI_ROTATIONS, + ] { + let synthesis = synthesize_numeric_2q_unitary(flat.as_ptr(), 1, 0, basis); + assert!(!synthesis.is_null(), "basis={basis}"); + assert!(two_qubit_synthesis_num_operations(synthesis) > 0); + assert!(two_qubit_synthesis_global_phase(synthesis).is_finite()); + two_qubit_synthesis_free(synthesis); + } + + let source = circuit_new(2); + let targets = [1, 0]; + assert_eq!( + circuit_unitary( + source, + name("boundary").as_ptr(), + 2, + flat.as_ptr(), + targets.as_ptr(), + 2 + ), + 0 + ); + let output = decompose_unitaries(source, decompose_unitary_config_default()); + assert!(!output.is_null()); + let matrix_of = |circuit| { + let len = circuit_to_matrix_len(circuit, std::ptr::null(), 0); + let mut values = vec![0.0; 2 * len]; + assert_eq!( + circuit_to_matrix( + circuit, + std::ptr::null(), + 0, + values.as_mut_ptr(), + values.len() + ), + len + ); + values + }; + assert!( + matrix_of(output) + .iter() + .zip(matrix_of(source)) + .all(|(a, b)| (a - b).abs() < 1e-9) + ); + circuit_free(output); + circuit_free(source); +} + // ===== Decomposition and resynthesis ===== #[test] diff --git a/crates/binding-c/tests/error_mitigation_test.rs b/crates/binding-c/tests/error_mitigation_test.rs index e02562e1..03734fc0 100644 --- a/crates/binding-c/tests/error_mitigation_test.rs +++ b/crates/binding-c/tests/error_mitigation_test.rs @@ -493,8 +493,11 @@ fn test_zne_run_em_sequence() { // ===== Fine-grained VirtualDistillation API (checklist section 5) ===== -/// Static estimator: numerator invocations (Hamiltonian present) report -/// (4.0, 0.1); denominator invocations (Hamiltonian NULL) report (2.0, 0.05). +/// Static estimator: numerator invocations report (4.0, 0.1); denominator +/// invocations report (2.0, 0.05). Both receive a non-NULL Hamiltonian now: +/// they are told apart by content — the denominator Hamiltonian is identity +/// on qubit 0 (a single X on the ancilla), while the numerator Hamiltonian +/// carries a non-identity Pauli on qubit 0 (the original Z term). extern "C" fn static_vd_estimator( _circuit: *const binding_c::circuit::CCircuit, hamiltonian: *const binding_c::qis::CHamiltonian, @@ -502,11 +505,14 @@ extern "C" fn static_vd_estimator( expectation: *mut f64, variance: *mut f64, ) { - if expectation.is_null() || variance.is_null() { + if expectation.is_null() || variance.is_null() || hamiltonian.is_null() { return; } unsafe { - if hamiltonian.is_null() { + let hamiltonian = &(*hamiltonian).inner; + let first_term = &hamiltonian.terms[0].0; + let is_denominator = !first_term.x[0] && !first_term.z[0]; + if is_denominator { *expectation = 2.0; *variance = 0.05; } else { @@ -557,7 +563,8 @@ fn test_virtual_distillation_run_vd_sampling() { pauli_string_free(pauli); // Numerator: the estimator sees the copy-swap circuit and the expanded - // Hamiltonian; denominator: no Hamiltonian. + // Hamiltonian (original Pauli on the first copy, X on the ancilla); + // denominator: an ancilla-X Hamiltonian with identity elsewhere. let mut num_mean = f64::NAN; let mut num_var = f64::NAN; assert_eq!( diff --git a/crates/binding-c/tests/parameter_test.rs b/crates/binding-c/tests/parameter_test.rs index 7afb1e84..87dc059d 100644 --- a/crates/binding-c/tests/parameter_test.rs +++ b/crates/binding-c/tests/parameter_test.rs @@ -22,6 +22,63 @@ fn eval(ptr: *const CParameter, bindings: &str) -> f64 { param_evaluate(ptr, cstr(bindings).as_ptr()) } +#[test] +fn param_substitution_swaps_symbols_simultaneously() { + let x = param_symbol(cstr("x").as_ptr()); + let y = param_symbol(cstr("y").as_ptr()); + let expression = param_parse(cstr("x + 2*y").as_ptr()); + let name_x = cstr("x"); + let name_y = cstr("y"); + for (names, values) in [ + ( + [name_x.as_ptr(), name_y.as_ptr()], + [y.cast_const(), x.cast_const()], + ), + ( + [name_y.as_ptr(), name_x.as_ptr()], + [x.cast_const(), y.cast_const()], + ), + ] { + for _ in 0..100 { + let result = param_substitute_many(expression, names.as_ptr(), values.as_ptr(), 2); + assert!(!result.is_null()); + let value = eval(result, "x:1,y:3"); + param_free(result); + assert_eq!(value, 5.0); + } + } + assert_eq!(eval(expression, "x:1,y:3"), 7.0); + for ptr in [x, y, expression] { + param_free(ptr); + } +} + +#[test] +fn param_substitution_reaches_polynomial_symbols() { + let x = param_symbol(cstr("x").as_ptr()); + let y = param_symbol(cstr("y").as_ptr()); + let square = param_mul(x, x); + let sum = param_add(square, x); + let one = param_from_double(1.0); + let expression = param_add(sum, one); + let name = cstr("x"); + let replaced = param_replace(expression, name.as_ptr(), y); + let substituted = param_substitute_many( + expression, + [name.as_ptr()].as_ptr(), + [y.cast_const()].as_ptr(), + 1, + ); + for result in [replaced, substituted] { + assert!(!result.is_null()); + assert_eq!(eval(result, "y:2"), 7.0); + param_free(result); + } + for ptr in [x, y, square, sum, one, expression] { + param_free(ptr); + } +} + #[test] fn param_construction_and_constants() { let theta = param_symbol(cstr("theta").as_ptr()); diff --git a/crates/binding-c/tests/parity_compile_em_test.rs b/crates/binding-c/tests/parity_compile_em_test.rs index efcc7873..a82b5d5c 100644 --- a/crates/binding-c/tests/parity_compile_em_test.rs +++ b/crates/binding-c/tests/parity_compile_em_test.rs @@ -145,8 +145,9 @@ fn test_virtual_distillation_build_copy_swap_circuit() { let copy_swap = virtual_distillation_build_copy_swap_circuit(vd); assert!(!copy_swap.is_null()); - // The copy-swap width is copies (2) times the base width (1). - assert_eq!(circuit_num_qubits(copy_swap), 2); + // The copy-swap width is copies (2) times the base width (1) plus one + // ancilla qubit. + assert_eq!(circuit_num_qubits(copy_swap), 3); assert!( circuit_num_operations(copy_swap) > 0, "copy-swap circuit should contain operations" diff --git a/crates/binding-c/tests/qis_algebra_test.rs b/crates/binding-c/tests/qis_algebra_test.rs new file mode 100644 index 00000000..3cd0b35f --- /dev/null +++ b/crates/binding-c/tests/qis_algebra_test.rs @@ -0,0 +1,630 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +use binding_c::{circuit::*, qis::*}; +use num_complex::Complex64 as C; +use std::ptr::{null, null_mut}; + +struct F(*mut CFermionicOp); +impl F { + fn make(call: impl FnOnce(*mut *mut CFermionicOp) -> i32) -> Self { + let mut out = null_mut(); + assert_eq!(call(&mut out), 0); + assert!(!out.is_null()); + Self(out) + } + fn mapped(&self) -> H { + H::make(|out| jordan_wigner_map_operator(self.0, out)) + } + fn equiv(&self, other: &Self) -> bool { + let mut result = 99; + assert_eq!(fermionic_op_equiv(self.0, other.0, 0.0, &mut result), 0); + result == 1 + } +} +impl Drop for F { + fn drop(&mut self) { + fermionic_op_free(self.0); + } +} +struct H(*mut CHamiltonian); +impl H { + fn make(call: impl FnOnce(*mut *mut CHamiltonian) -> i32) -> Self { + let mut out = null_mut(); + assert_eq!(call(&mut out), 0); + assert!(!out.is_null()); + Self(out) + } + fn from_pauli(text: &std::ffi::CStr, coefficient: C) -> Self { + let p = pauli_string_parse(text.as_ptr()); + assert!(!p.is_null()); + let terms = [CHamiltonianTerm { + pauli: p, + coefficient, + }]; + let h = Self::make(|out| { + hamiltonian_from_terms(pauli_string_num_qubits(p), terms.as_ptr(), 1, out) + }); + pauli_string_free(p); + h + } + fn equiv(&self, other: &Self) -> bool { + let mut result = 99; + assert_eq!(hamiltonian_equiv(self.0, other.0, 0.0, &mut result), 0); + result == 1 + } + fn matrix(&self) -> Vec { + let dim = hamiltonian_to_matrix_len(self.0); + let mut result = vec![C::default(); dim * dim]; + assert_eq!( + hamiltonian_to_matrix(self.0, result.as_mut_ptr(), result.len()), + 0 + ); + result + } +} +impl Drop for H { + fn drop(&mut self) { + hamiltonian_free(self.0); + } +} + +#[test] +fn empty_spaces_and_owned_snapshots() { + let zero = F::make(|out| fermionic_op_from_terms(0, null(), 0, out)); + let identity = F::make(|out| fermionic_op_from_term(0, null(), 0, C::new(1.0, 0.0), out)); + let total = F::make(|out| fermionic_op_total_number(0, out)); + assert!(zero.equiv(&total)); + assert!(!zero.equiv(&identity)); + let mut n = 99; + assert_eq!(fermionic_op_num_modes(zero.0, &mut n), 0); + assert_eq!(n, 0); + assert_eq!(fermionic_op_num_terms(identity.0, &mut n), 0); + assert_eq!(n, 1); + assert_eq!(fermionic_op_term_len(identity.0, 0, &mut n), 0); + assert_eq!(n, 0); + let mut coefficient = C::default(); + assert_eq!( + fermionic_op_get_term(identity.0, 0, null_mut(), 0, &mut coefficient), + 0 + ); + assert_eq!(coefficient, C::new(1.0, 0.0)); + let h = identity.mapped(); + let mut pauli = null_mut(); + assert_eq!( + hamiltonian_get_term(h.0, 0, &mut pauli, &mut coefficient), + 0 + ); + drop(h); + assert_eq!(pauli_string_num_qubits(pauli), 0); + pauli_string_free(pauli); + let scalar = H::make(|out| hamiltonian_identity(0, out)); + assert_eq!(scalar.matrix(), vec![C::new(1.0, 0.0)]); + let huge_zero = F::make(|out| fermionic_op_new(usize::MAX, out)); + let mapped = huge_zero.mapped(); + assert_eq!(hamiltonian_num_qubits(mapped.0), usize::MAX); + let huge_identity = F::make(|out| fermionic_op_identity(usize::MAX, out)); + let mut out = scalar.0; + assert_eq!(jordan_wigner_map_operator(huge_identity.0, &mut out), -7); + assert_eq!(out, scalar.0); + assert_eq!(hamiltonian_identity(usize::MAX, &mut out), -7); + assert_eq!(out, scalar.0); +} + +#[test] +fn anticommutation_normal_order_and_structural_equality() { + let a = F::make(|out| fermionic_op_annihilation(2, 0, out)); + let creator = F::make(|out| fermionic_op_creation(2, 0, out)); + let ac = F::make(|out| fermionic_op_mul(a.0, creator.0, out)); + let ca = F::make(|out| fermionic_op_mul(creator.0, a.0, out)); + let sum = F::make(|out| fermionic_op_add(ac.0, ca.0, out)); + let identity = F::make(|out| fermionic_op_identity(2, out)); + assert!(sum.equiv(&identity)); + let mut same = 99; + assert_eq!(fermionic_op_equals(sum.0, identity.0, &mut same), 0); + assert_eq!(same, 0); + let ordered = F::make(|out| fermionic_op_normal_order(sum.0, out)); + assert_eq!(fermionic_op_equals(ordered.0, identity.0, &mut same), 0); + assert_eq!(same, 1); + let square = F::make(|out| fermionic_op_mul(a.0, a.0, out)); + assert_eq!(fermionic_op_is_zero(square.0, &mut same), 0); + assert_eq!(same, 0); + let ordered = F::make(|out| fermionic_op_normal_order(square.0, out)); + assert_eq!(fermionic_op_is_zero(ordered.0, &mut same), 0); + assert_eq!(same, 1); + let other = F::make(|out| fermionic_op_creation(2, 1, out)); + let ao = F::make(|out| fermionic_op_mul(a.0, other.0, out)); + let oa = F::make(|out| fermionic_op_mul(other.0, a.0, out)); + let cross = F::make(|out| fermionic_op_add(ao.0, oa.0, out)); + let zero = F::make(|out| fermionic_op_new(2, out)); + assert!(cross.equiv(&zero)); + let adjoint = F::make(|out| fermionic_op_adjoint(a.0, out)); + assert_eq!(fermionic_op_equals(adjoint.0, creator.0, &mut same), 0); + assert_eq!(same, 1); + let copy = F::make(|out| fermionic_op_copy(creator.0, out)); + assert_eq!(fermionic_op_chop(copy.0, 1.0), 0); + assert!(!copy.equiv(&creator)); +} + +#[test] +fn excitation_order_signs_and_number_conservation() { + let source = [0, 1]; + let target = [2, 3]; + let generator = F::make(|out| { + fermionic_op_excitation_generator(4, source.as_ptr(), 2, target.as_ptr(), 2, out) + }); + let reversed = [3, 2]; + let swapped = F::make(|out| { + fermionic_op_excitation_generator(4, source.as_ptr(), 2, reversed.as_ptr(), 2, out) + }); + let negative = F::make(|out| fermionic_op_scaled(generator.0, C::new(-1.0, 0.0), out)); + assert!(swapped.equiv(&negative)); + let mut yes = 99; + assert_eq!(fermionic_op_is_hermitian(generator.0, 0.0, &mut yes), 0); + assert_eq!(yes, 1); + let number = F::make(|out| fermionic_op_total_number(4, out)); + let ng = F::make(|out| fermionic_op_mul(number.0, generator.0, out)); + let gn = F::make(|out| fermionic_op_mul(generator.0, number.0, out)); + let commutator = F::make(|out| fermionic_op_sub(ng.0, gn.0, out)); + let zero = F::make(|out| fermionic_op_new(4, out)); + assert!(commutator.equiv(&zero)); + let mut out = generator.0; + for (sources, targets, expected) in [ + (&[][..], &[][..], -8), + (&source[..], &target[..1], -8), + (&[0, 0][..], &target[..], -8), + (&source[..], &[1, 3][..], -8), + (&source[..], &[2, 4][..], -2), + ] { + assert_eq!( + fermionic_op_excitation_generator( + 4, + sources.as_ptr(), + sources.len(), + targets.as_ptr(), + targets.len(), + &mut out + ), + expected + ); + assert_eq!(out, generator.0); + } +} + +#[test] +fn jordan_wigner_signs_occupations_and_nonhermitian_results() { + let creator = F::make(|out| fermionic_op_creation(1, 0, out)); + let annihilator = F::make(|out| fermionic_op_annihilation(1, 0, out)); + let creation_matrix = creator.mapped().matrix(); + assert_eq!( + creation_matrix, + vec![C::default(), C::default(), C::new(1.0, 0.0), C::default()] + ); + assert_eq!( + annihilator.mapped().matrix(), + vec![C::default(), C::new(1.0, 0.0), C::default(), C::default()] + ); + let number = F::make(|out| fermionic_op_number(1, 0, out)); + assert_eq!( + number.mapped().matrix(), + vec![C::default(), C::default(), C::default(), C::new(1.0, 0.0)] + ); + let high = F::make(|out| fermionic_op_creation(2, 1, out)); + let matrix = high.mapped().matrix(); + assert_eq!(matrix[2 * 4], C::new(1.0, 0.0)); + assert_eq!(matrix[3 * 4 + 1], C::new(-1.0, 0.0)); + let mut bits = [99; 4]; + let occupation = [1, 0, 1]; + assert_eq!( + jordan_wigner_map_occupation(occupation.as_ptr(), 3, bits.as_mut_ptr(), 4), + 0 + ); + assert_eq!(bits, [1, 0, 1, 99]); + let before = bits; + assert_eq!( + jordan_wigner_map_occupation([1, 2, 0].as_ptr(), 3, bits.as_mut_ptr(), 4), + -8 + ); + assert_eq!(bits, before); + assert_eq!( + jordan_wigner_map_occupation(occupation.as_ptr(), 3, bits.as_mut_ptr(), 2), + -8 + ); + assert_eq!(bits, before); + assert_eq!(jordan_wigner_map_occupation(null(), 0, null_mut(), 0), 0); + assert_eq!( + jordan_wigner_map_occupation(bits.as_ptr(), 3, bits.as_mut_ptr(), 4), + 0 + ); + let mut n = 99; + assert_eq!(jordan_wigner_num_qubits(3, &mut n), 0); + assert_eq!(n, 3); +} + +#[test] +fn checked_pauli_phases_tensor_and_remap() { + let x = H::from_pauli(c"X", C::new(1.0, 0.0)); + let z = H::from_pauli(c"Z", C::new(1.0, 0.0)); + let minus_i_y = H::from_pauli(c"Y", C::new(0.0, -1.0)); + let xz = H::make(|out| hamiltonian_mul(x.0, z.0, out)); + assert!(xz.equiv(&minus_i_y)); + let dagger = H::make(|out| hamiltonian_adjoint(xz.0, out)); + let negative = H::make(|out| hamiltonian_scaled(xz.0, C::new(-1.0, 0.0), out)); + assert!(dagger.equiv(&negative)); + let sum = H::make(|out| hamiltonian_add(x.0, z.0, out)); + let difference = H::make(|out| hamiltonian_sub(sum.0, z.0, out)); + assert!(difference.equiv(&x)); + let tensor = H::make(|out| hamiltonian_tensor(x.0, z.0, out)); + let expected = H::from_pauli(c"XZ", C::new(1.0, 0.0)); + assert!(tensor.equiv(&expected)); + let embed = H::make(|out| hamiltonian_remap_qubits(x.0, [2].as_ptr(), 1, 3, out)); + let expected = H::from_pauli(c"XII", C::new(1.0, 0.0)); + assert!(embed.equiv(&expected)); + let mut out = embed.0; + assert_eq!( + hamiltonian_remap_qubits(tensor.0, [0, 0].as_ptr(), 2, 3, &mut out), + -8 + ); + assert_eq!( + hamiltonian_remap_qubits(x.0, [3].as_ptr(), 1, 3, &mut out), + -8 + ); + assert_eq!(hamiltonian_remap_qubits(x.0, null(), 0, 3, &mut out), -8); + assert_eq!(out, embed.0); + let zero = H::make(|out| hamiltonian_from_terms(0, null(), 0, out)); + let scalar_embed = H::make(|out| hamiltonian_remap_qubits(zero.0, null(), 0, 3, out)); + assert_eq!(hamiltonian_num_qubits(scalar_embed.0), 3); + let phased = H::from_pauli(c"iX", C::new(0.0, -1.0)); + assert!(phased.equiv(&x)); +} + +#[test] +fn nonzero_coefficients_projection_and_legacy_semantics() { + let tiny = 1e-20; + let creator = F::make(|out| fermionic_op_creation(1, 0, out)); + let scaled = F::make(|out| fermionic_op_scaled(creator.0, C::new(tiny, 0.0), out)); + let mut n = 99; + assert_eq!(fermionic_op_num_terms(scaled.0, &mut n), 0); + assert_eq!(n, 1); + let mapped = scaled.mapped(); + assert_eq!(hamiltonian_num_terms(mapped.0), 2); + let h = H::from_pauli(c"X", C::new(tiny, 0.0)); + let normalized = H::make(|out| hamiltonian_normalized(h.0, out)); + assert_eq!(hamiltonian_num_terms(normalized.0), 1); + let copy = H::make(|out| hamiltonian_copy(h.0, out)); + assert_eq!(hamiltonian_simplify(copy.0), 0); + assert_eq!(hamiltonian_num_terms(copy.0), 0); + assert_eq!(hamiltonian_num_terms(h.0), 1); + assert_eq!(hamiltonian_chop(normalized.0, tiny), 0); + assert_eq!(hamiltonian_num_terms(normalized.0), 0); + let residual = H::from_pauli(c"Z", C::new(2.0, 4e-11)); + let mut yes = 99; + assert_eq!(hamiltonian_is_hermitian(residual.0, 0.0, &mut yes), 0); + assert_eq!(yes, 0); + assert_eq!(hamiltonian_is_hermitian(residual.0, 8e-11, &mut yes), 0); + assert_eq!(yes, 1); + let projected = H::make(|out| hamiltonian_normalized_hermitian(residual.0, out)); + let real = H::from_pauli(c"Z", C::new(2.0, 0.0)); + assert!(projected.equiv(&real)); + let imaginary = H::from_pauli(c"Z", C::new(2.0, 2e-10)); + let mut out = real.0; + assert_eq!(hamiltonian_normalized_hermitian(imaginary.0, &mut out), -8); + assert_eq!(out, real.0); +} + +#[test] +fn invalid_coefficients_atomicity_and_array_contracts() { + let creator = F::make(|out| fermionic_op_creation(1, 0, out)); + let snapshot = F::make(|out| fermionic_op_copy(creator.0, out)); + let ladder = CFermionicLadder { + mode: 0, + kind: FERMIONIC_CREATE, + }; + let mut out = creator.0; + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert_eq!( + fermionic_op_add_term(creator.0, &ladder, 1, C::new(bad, 0.0)), + -8 + ); + assert!(creator.equiv(&snapshot)); + assert_eq!( + fermionic_op_scaled(creator.0, C::new(0.0, bad), &mut out), + -8 + ); + assert_eq!(out, creator.0); + } + for bad in [-1.0, f64::NAN, f64::INFINITY] { + assert_eq!(fermionic_op_chop(creator.0, bad), -8); + assert!(creator.equiv(&snapshot)); + let mut result = 99; + assert_eq!( + fermionic_op_equiv(creator.0, snapshot.0, bad, &mut result), + -8 + ); + assert_eq!(result, 99); + } + let invalid = CFermionicLadder { mode: 0, kind: 255 }; + assert_eq!( + fermionic_op_from_term(1, &invalid, 1, C::default(), &mut out), + -8 + ); + let invalid = CFermionicLadder { + mode: 1, + kind: FERMIONIC_CREATE, + }; + assert_eq!( + fermionic_op_from_term(1, &invalid, 1, C::default(), &mut out), + -2 + ); + assert_eq!( + fermionic_op_from_term(1, &ladder, usize::MAX, C::default(), &mut out), + -8 + ); + assert_eq!(fermionic_op_from_terms(1, null(), 1, &mut out), -1); + let mut buffer = [CFermionicLadder { mode: 99, kind: 99 }; 2]; + let mut coefficient = C::new(99.0, 99.0); + assert_eq!( + fermionic_op_get_term(creator.0, 0, buffer.as_mut_ptr(), 0, &mut coefficient), + -8 + ); + assert_eq!(buffer[0].mode, 99); + assert_eq!(coefficient, C::new(99.0, 99.0)); + assert_eq!( + fermionic_op_get_term(creator.0, 9, buffer.as_mut_ptr(), 2, &mut coefficient), + -2 + ); + assert_eq!( + fermionic_op_get_term(creator.0, 0, null_mut(), 2, &mut coefficient), + -1 + ); + assert_eq!( + fermionic_op_get_term(creator.0, 0, buffer.as_mut_ptr(), 2, &mut coefficient), + 0 + ); + assert_eq!((buffer[0].mode, buffer[0].kind), (0, FERMIONIC_CREATE)); + assert_eq!(buffer[1].mode, 99); + buffer[0].kind = FERMIONIC_ANNIHILATE; + assert_eq!(buffer[0].kind, FERMIONIC_ANNIHILATE); + assert!(creator.equiv(&snapshot)); + let huge = F::make(|out| fermionic_op_from_term(1, &ladder, 1, C::new(f64::MAX, 0.0), out)); + let mut out = creator.0; + assert_eq!(fermionic_op_add(huge.0, huge.0, &mut out), -8); + assert_eq!( + fermionic_op_add_term(huge.0, &ladder, 1, C::new(f64::MAX, 0.0)), + -8 + ); + assert_eq!(fermionic_op_scaled(huge.0, C::new(2.0, 0.0), &mut out), -8); + assert_eq!(out, creator.0); + assert_eq!(fermionic_op_creation(1, 1, &mut out), -2); + let wrong_width = F::make(|out| fermionic_op_new(2, out)); + assert_eq!(fermionic_op_mul(creator.0, wrong_width.0, &mut out), -8); + assert_eq!(out, creator.0); +} + +#[test] +fn checked_hamiltonian_validates_legacy_storage_without_overwriting_outputs() { + let p = pauli_string_parse(c"X".as_ptr()); + let h = H(hamiltonian_new(1)); + assert_eq!(hamiltonian_add_term(h.0, p, f64::NAN, 0.0), 0); // legacy behavior + pauli_string_free(p); + let snapshot = unsafe { (*h.0).inner.clone() }; + let valid = H::from_pauli(c"Z", C::new(1.0, 0.0)); + let mut out = valid.0; + assert_eq!(hamiltonian_normalized(h.0, &mut out), -8); + assert_eq!(hamiltonian_scaled(h.0, C::new(1.0, 0.0), &mut out), -8); + assert_eq!(hamiltonian_add(h.0, valid.0, &mut out), -8); + assert_eq!(hamiltonian_chop(h.0, 0.0), -8); + assert_eq!(out, valid.0); + assert!(unsafe { (&(*h.0).inner.terms)[0].1.re.is_nan() }); + assert_eq!(unsafe { (*h.0).inner.terms.len() }, snapshot.terms.len()); + let large = H::from_pauli(c"X", C::new(f64::MAX, 0.0)); + assert_eq!(hamiltonian_add(large.0, large.0, &mut out), -8); + assert_eq!(hamiltonian_scaled(large.0, C::new(2.0, 0.0), &mut out), -8); + let p = pauli_string_parse(c"X".as_ptr()); + let terms = [ + CHamiltonianTerm { + pauli: p, + coefficient: C::new(f64::MAX, 0.0), + }, + CHamiltonianTerm { + pauli: p, + coefficient: C::new(f64::MAX, 0.0), + }, + ]; + assert_eq!(hamiltonian_from_terms(1, terms.as_ptr(), 2, &mut out), -8); + assert_eq!(hamiltonian_from_terms(2, terms.as_ptr(), 1, &mut out), -8); + assert_eq!( + hamiltonian_from_terms(1, terms.as_ptr(), usize::MAX, &mut out), + -8 + ); + pauli_string_free(p); + for bad in [-1.0, f64::NAN, f64::INFINITY] { + let mut yes = 99; + assert_eq!(hamiltonian_chop(valid.0, bad), -8); + assert_eq!(hamiltonian_is_hermitian(valid.0, bad, &mut yes), -8); + assert_eq!(yes, 99); + } + let mut copied = null_mut(); + let mut coefficient = C::new(99.0, 0.0); + assert_eq!( + hamiltonian_get_term(valid.0, 9, &mut copied, &mut coefficient), + -2 + ); + assert!(copied.is_null()); + assert_eq!(coefficient.re, 99.0); + assert_eq!( + hamiltonian_get_term(valid.0, 0, &mut copied, &mut coefficient), + 0 + ); + assert_eq!(pauli_string_set_pauli(copied, 0, PAULI_X), 0); + pauli_string_free(copied); + assert_eq!( + valid.matrix(), + vec![ + C::new(1.0, 0.0), + C::default(), + C::default(), + C::new(-1.0, 0.0) + ] + ); +} + +#[test] +fn excitation_to_evolution_and_numeric_phase_regressions() { + let generator = + F::make(|out| fermionic_op_excitation_generator(2, [0].as_ptr(), 1, [1].as_ptr(), 1, out)); + let mapped = generator.mapped(); + let theta: f64 = 0.37; + let evolution = hamiltonian_to_evolution_circuit(mapped.0, theta, 1, TROTTER_MODE_SECOND_ORDER); + assert!(!evolution.is_null()); + let state = [C::default(), C::new(1.0, 0.0), C::default(), C::default()]; + let sv = statevector_from_state(2, state.as_ptr(), 4); + assert_eq!(statevector_apply_circuit(sv, evolution), 0); + let mut data = [C::default(); 4]; + assert_eq!(statevector_data(sv, data.as_mut_ptr(), 4), 0); + assert!((data[1] - C::new(theta.cos(), 0.0)).norm() < 1e-12); + assert!((data[2] - C::new(theta.sin(), 0.0)).norm() < 1e-12); + assert!(data[0].norm() < 1e-12 && data[3].norm() < 1e-12); + statevector_free(sv); + circuit_free(evolution); + let phase = circuit_new(1); + assert_eq!(circuit_set_global_phase(phase, 0.37), 0); + let sv = statevector_from_circuit(phase); + let mut data = [C::default(); 2]; + assert_eq!(statevector_data(sv, data.as_mut_ptr(), 2), 0); + assert!((data[0] - C::from_polar(1.0, 0.37)).norm() < 1e-12); + statevector_free(sv); + circuit_free(phase); + let a = param_from_double(1e-20); + let b = param_from_double(2.0); + let product = param_mul(a, b); + assert_eq!(param_evaluate(product, null()), 2e-20); + param_free(product); + param_free(a); + param_free(b); +} + +#[test] +fn all_checked_entry_points_reject_required_null_pointers() { + assert_eq!(fermionic_op_new(1, null_mut()), -1); + assert_eq!(fermionic_op_identity(1, null_mut()), -1); + assert_eq!(fermionic_op_total_number(1, null_mut()), -1); + assert_eq!(fermionic_op_creation(1, 1, null_mut()), -1); + assert_eq!(fermionic_op_annihilation(1, 1, null_mut()), -1); + assert_eq!(fermionic_op_number(1, 1, null_mut()), -1); + assert_eq!( + fermionic_op_from_term(1, null(), 1, C::default(), null_mut()), + -1 + ); + assert_eq!(fermionic_op_from_terms(1, null(), 1, null_mut()), -1); + assert_eq!( + fermionic_op_add_term(null_mut(), null(), 1, C::default()), + -1 + ); + assert_eq!( + fermionic_op_excitation_generator(1, null(), 1, null(), 1, null_mut()), + -1 + ); + assert_eq!(fermionic_op_num_modes(null(), null_mut()), -1); + assert_eq!(fermionic_op_num_terms(null(), null_mut()), -1); + assert_eq!(fermionic_op_is_zero(null(), null_mut()), -1); + assert_eq!(fermionic_op_copy(null(), null_mut()), -1); + assert_eq!(fermionic_op_adjoint(null(), null_mut()), -1); + assert_eq!(fermionic_op_normal_order(null(), null_mut()), -1); + assert_eq!(fermionic_op_add(null(), null(), null_mut()), -1); + assert_eq!(fermionic_op_sub(null(), null(), null_mut()), -1); + assert_eq!(fermionic_op_mul(null(), null(), null_mut()), -1); + assert_eq!(fermionic_op_scaled(null(), C::default(), null_mut()), -1); + assert_eq!(fermionic_op_chop(null_mut(), 0.0), -1); + assert_eq!(fermionic_op_equals(null(), null(), null_mut()), -1); + assert_eq!(fermionic_op_equiv(null(), null(), 0.0, null_mut()), -1); + assert_eq!(fermionic_op_is_hermitian(null(), 0.0, null_mut()), -1); + assert_eq!(fermionic_op_term_len(null(), 1, null_mut()), -1); + assert_eq!( + fermionic_op_get_term(null(), 1, null_mut(), 1, null_mut()), + -1 + ); + assert_eq!(jordan_wigner_map_operator(null(), null_mut()), -1); + assert_eq!(jordan_wigner_num_qubits(1, null_mut()), -1); + assert_eq!(jordan_wigner_map_occupation(null(), 1, null_mut(), 1), -1); + assert_eq!(hamiltonian_identity(1, null_mut()), -1); + assert_eq!(hamiltonian_from_terms(1, null(), 1, null_mut()), -1); + assert_eq!(hamiltonian_copy(null(), null_mut()), -1); + assert_eq!(hamiltonian_normalized(null(), null_mut()), -1); + assert_eq!(hamiltonian_normalized_hermitian(null(), null_mut()), -1); + assert_eq!(hamiltonian_adjoint(null(), null_mut()), -1); + assert_eq!(hamiltonian_add(null(), null(), null_mut()), -1); + assert_eq!(hamiltonian_sub(null(), null(), null_mut()), -1); + assert_eq!(hamiltonian_mul(null(), null(), null_mut()), -1); + assert_eq!(hamiltonian_tensor(null(), null(), null_mut()), -1); + assert_eq!(hamiltonian_scaled(null(), C::default(), null_mut()), -1); + assert_eq!( + hamiltonian_remap_qubits(null(), null(), 1, 1, null_mut()), + -1 + ); + assert_eq!(hamiltonian_chop(null_mut(), 0.0), -1); + assert_eq!(hamiltonian_equiv(null(), null(), 0.0, null_mut()), -1); + assert_eq!(hamiltonian_is_hermitian(null(), 0.0, null_mut()), -1); + assert_eq!(hamiltonian_get_term(null(), 1, null_mut(), null_mut()), -1); +} + +#[test] +fn wide_sparse_registers_reject_dense_sizes_without_panicking_or_writing() { + let bits = usize::BITS as usize; + // Exercise side-length, element-count and byte-count overflow separately. + for width in [ + bits, + bits + 1, + bits - 1, + bits / 2, + bits / 2 - 1, + bits / 2 - 2, + ] { + let identity = F::make(|out| fermionic_op_identity(width, out)); + let mapped = identity.mapped(); + let mut pauli = null_mut(); + let mut coefficient = C::default(); + assert_eq!( + hamiltonian_get_term(mapped.0, 0, &mut pauli, &mut coefficient), + 0 + ); + let expected_dim = if width < bits { 1usize << width } else { 0 }; + assert_eq!(hamiltonian_to_matrix_len(mapped.0), expected_dim); + assert_eq!(pauli_string_matrix_len(pauli), expected_dim); + let sentinel = C::new(99.0, -99.0); + let mut buffer = sentinel; + assert_eq!(hamiltonian_to_matrix(mapped.0, &mut buffer, 1), -7); + assert_eq!(buffer, sentinel); + assert_eq!(pauli_string_matrix(pauli, &mut buffer, 1), -7); + assert_eq!(buffer, sentinel); + pauli_string_free(pauli); + } + let zero = F::make(|out| fermionic_op_new(usize::MAX, out)).mapped(); + assert_eq!(hamiltonian_to_matrix_len(zero.0), 0); + let mut buffer = C::new(99.0, -99.0); + assert_eq!(hamiltonian_to_matrix(zero.0, &mut buffer, 1), -7); + assert_eq!(buffer, C::new(99.0, -99.0)); + // A valid width with a tiny buffer must be rejected before dense allocation. + let identity = H::make(|out| hamiltonian_identity(20, out)); + let mut pauli = null_mut(); + let mut coefficient = C::default(); + assert_eq!( + hamiltonian_get_term(identity.0, 0, &mut pauli, &mut coefficient), + 0 + ); + assert_eq!(hamiltonian_to_matrix(identity.0, &mut buffer, 1), -8); + assert_eq!(pauli_string_matrix(pauli, &mut buffer, 1), -8); + assert_eq!(buffer, C::new(99.0, -99.0)); + pauli_string_free(pauli); + assert_eq!(hamiltonian_to_matrix_len(null()), 0); + assert_eq!(pauli_string_matrix_len(null()), 0); +} diff --git a/crates/binding-c/tests/qis_constructor_regressions.rs b/crates/binding-c/tests/qis_constructor_regressions.rs new file mode 100644 index 00000000..6fc86bae --- /dev/null +++ b/crates/binding-c/tests/qis_constructor_regressions.rs @@ -0,0 +1,51 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Invalid dimensions must return NULL instead of unwinding across the C ABI. +use binding_c::qis::*; + +#[test] +fn invalid_dimensions_return_null() { + for n in [usize::BITS as usize - 4, usize::BITS as usize, usize::MAX] { + assert!(statevector_new(n).is_null()); + } + for n in [ + (usize::BITS as usize - 4).div_ceil(2), + usize::BITS as usize, + usize::MAX, + ] { + assert!(density_matrix_new(n).is_null()); + assert!(density_matrix_zeros(n).is_null()); + assert!(density_matrix_maximally_mixed(n).is_null()); + assert!(density_matrix_noise_new(n, std::ptr::null()).is_null()); + } +} + +#[test] +fn normal_and_zero_qubit_constructors_remain_valid() { + for n in [0, 1, 3] { + let sv = statevector_new(n); + assert!(!sv.is_null()); + statevector_free(sv); + for dm in [ + density_matrix_new(n), + density_matrix_zeros(n), + density_matrix_maximally_mixed(n), + ] { + assert!(!dm.is_null()); + density_matrix_free(dm); + } + let noisy = density_matrix_noise_new(n, std::ptr::null()); + assert!(!noisy.is_null()); + density_matrix_noise_free(noisy); + } +} diff --git a/crates/binding-c/tests/qis_noise_test.rs b/crates/binding-c/tests/qis_noise_test.rs index 989e236e..21f69a3b 100644 --- a/crates/binding-c/tests/qis_noise_test.rs +++ b/crates/binding-c/tests/qis_noise_test.rs @@ -2,7 +2,9 @@ #![allow(dead_code)] -use binding_c::circuit::{circuit_cx, circuit_free, circuit_h, circuit_new, circuit_x}; +use binding_c::circuit::{ + circuit_cx, circuit_free, circuit_from_qubits, circuit_h, circuit_new, circuit_x, +}; use binding_c::cqlib_string_free; use binding_c::device::{ NOISE_BIT_FLIP, noise_model_add_readout, noise_model_add_single_qubit, noise_model_free, @@ -216,6 +218,42 @@ fn test_readout_error_difference() { noise_model_free(nm); } +#[test] +fn test_readout_uses_circuit_ids_at_storage_positions() { + for ids in [[0, 1], [1, 0], [2, 0], [9, 2]] { + let circuit = circuit_from_qubits(ids.as_ptr(), ids.len()); + assert!(!circuit.is_null()); + let model = noise_model_new(); + assert_eq!(noise_model_add_readout(model, ids[0], 0.0, 1.0), 0); + let sim = density_matrix_noise_from_circuit(circuit, model); + assert!(!sim.is_null()); + assert_eq!(density_matrix_noise_probabilities_with_readout_len(sim), 4); + for (positions, expected) in [ + (&[0][..], [0.0, 1.0, 0.0, 0.0]), + (&[1][..], [1.0, 0.0, 0.0, 0.0]), + (&[1, 0][..], [0.0, 1.0, 0.0, 0.0]), + (&[][..], [1.0, 0.0, 0.0, 0.0]), + ] { + let mut actual = [0.0; 4]; + assert_eq!( + density_matrix_noise_probabilities_with_readout( + sim, + actual.as_mut_ptr(), + actual.len(), + positions.as_ptr(), + positions.len() + ), + 0 + ); + assert_eq!(actual, expected); + } + assert_eq!(read_probs(sim, 4), vec![1.0, 0.0, 0.0, 0.0]); + density_matrix_noise_free(sim); + noise_model_free(model); + circuit_free(circuit); + } +} + #[test] fn test_multi_qubit_readout() { // Mirrors core `test_multi_qubit_readout_error`. diff --git a/crates/binding-c/tests/qis_p2_regressions.rs b/crates/binding-c/tests/qis_p2_regressions.rs new file mode 100644 index 00000000..5e532b95 --- /dev/null +++ b/crates/binding-c/tests/qis_p2_regressions.rs @@ -0,0 +1,49 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +use binding_c::qis::*; +use num_complex::Complex64; + +#[test] +fn nonfinite_states_return_null() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX] { + for value in [Complex64::new(bad, 0.0), Complex64::new(0.0, bad)] { + let data = [value, Complex64::new(0.0, 0.0)]; + assert!(statevector_from_state(1, data.as_ptr(), data.len()).is_null()); + assert!(density_matrix_from_state(1, data.as_ptr(), data.len()).is_null()); + } + } +} + +#[test] +fn nonhermitian_expectation_reports_error_without_overwriting_output() { + let sv = statevector_new(1); + let dm = density_matrix_new(1); + let h = hamiltonian_new(1); + let p = pauli_string_parse(c"Z".as_ptr()); + assert_eq!(hamiltonian_add_term(h, p, 0.0, 1.0), 0); + let mut out = 123.0; + assert_ne!(statevector_expectation(sv, h, &mut out), 0); + assert_eq!(out, 123.0); + assert_ne!(density_matrix_expectation(dm, h, &mut out), 0); + assert_eq!(out, 123.0); + // The imaginary parts cancel: the observable is now Z. + assert_eq!(hamiltonian_add_term(h, p, 1.0, -1.0), 0); + assert_eq!(statevector_expectation(sv, h, &mut out), 0); + assert_eq!(out, 1.0); + assert_eq!(density_matrix_expectation(dm, h, &mut out), 0); + assert_eq!(out, 1.0); + pauli_string_free(p); + hamiltonian_free(h); + statevector_free(sv); + density_matrix_free(dm); +} diff --git a/crates/binding-c/tests/qis_test.rs b/crates/binding-c/tests/qis_test.rs index 05e2174d..ddc13132 100644 --- a/crates/binding-c/tests/qis_test.rs +++ b/crates/binding-c/tests/qis_test.rs @@ -165,6 +165,61 @@ fn test_density_matrix_partial_trace() { density_matrix_free(dm); } +#[test] +fn density_matrix_duplicate_gate_targets_preserve_state() { + let dm = density_matrix_new(2); + assert!(!dm.is_null()); + assert_eq!(density_matrix_apply_h(dm, 0), 0); + let mut before = vec![num_complex::Complex64::default(); 16]; + assert_eq!(density_matrix_data(dm, before.as_mut_ptr(), 16), 0); + for q in [0, 1] { + assert_eq!(density_matrix_apply_cx(dm, q, q), -8); + assert_eq!(density_matrix_apply_cz(dm, q, q), -8); + let mut after = before.clone(); + assert_eq!(density_matrix_data(dm, after.as_mut_ptr(), 16), 0); + assert_eq!(after, before); + } + assert_eq!(density_matrix_apply_cx(dm, 0, 1), 0); + density_matrix_free(dm); +} + +#[test] +fn density_matrix_duplicate_kraus_targets_preserve_state() { + let state: Vec<_> = (1..=4) + .map(|i| num_complex::Complex64::new(i as f64 / 30.0_f64.sqrt(), 0.0)) + .collect(); + let dm = density_matrix_from_state(2, state.as_ptr(), state.len()); + assert!(!dm.is_null()); + let vector = [4.0, -1.0, 2.0, 3.0]; + let operator: Vec<_> = (0..4) + .flat_map(|r| { + (0..4).map(move |c| { + num_complex::Complex64::new( + if r == c { 1.0 } else { 0.0 } - 2.0 * vector[r] * vector[c] / 30.0, + 0.0, + ) + }) + }) + .collect(); + let mut before = vec![num_complex::Complex64::default(); 16]; + assert_eq!(density_matrix_data(dm, before.as_mut_ptr(), 16), 0); + for q in [0, 1] { + let targets = [q, q]; + assert_eq!( + density_matrix_apply_kraus(dm, operator.as_ptr(), 1, 4, targets.as_ptr(), 2), + -8 + ); + let mut after = before.clone(); + assert_eq!(density_matrix_data(dm, after.as_mut_ptr(), 16), 0); + assert_eq!(after, before); + } + assert_eq!( + density_matrix_apply_kraus(dm, operator.as_ptr(), 1, 4, [0, 1].as_ptr(), 2), + 0 + ); + density_matrix_free(dm); +} + #[test] fn test_stabilizer_new_and_clifford() { let ss = stabilizer_new(2); diff --git a/crates/binding-c/tests/test_circuit.c b/crates/binding-c/tests/test_circuit.c index f1f33944..aebce651 100644 --- a/crates/binding-c/tests/test_circuit.c +++ b/crates/binding-c/tests/test_circuit.c @@ -165,11 +165,225 @@ static void test_extended_gates(void) { circuit_free(circuit); } +static void test_circuit_gate_operation_matrix(void) { + const uint32_t orders[][2] = {{0, 1}, {1, 0}, {7, 2}}; + const uint32_t targets[] = {0, 1}; + for (size_t order = 0; order < 3; ++order) { + for (int parameterized = 0; parameterized < 2; ++parameterized) { + CCircuit* body = circuit_new(0); + assert(body != NULL); + assert(circuit_add_qubits(body, orders[order], 2) == 0); + /* Build on dense ids, then map into the explicit storage order. */ + CCircuit* definition = circuit_new(2); + assert(definition != NULL); + CParameter* theta = param_parse("theta"); + assert(theta != NULL); + if (parameterized) { + assert(circuit_rx_param(definition, 0, theta) == 0); + } else { + assert(circuit_x(definition, 0) == 0); + } + assert(circuit_compose(body, definition, orders[order], 2) == 0); + circuit_free(definition); + assert(circuit_set_global_phase(body, 0.13) == 0); + CCircuitGate* gate = circuit_to_gate(body, "first_gate"); + assert(gate != NULL); + for (size_t application = 0; application < 2; ++application) { + double angle = application == 0 ? 0.37 : -0.61; + CParameter* argument = param_from_double(angle); + const CParameter* arguments[] = {argument}; + assert(argument != NULL); + CCircuit* circuit = circuit_new(2); + assert(circuit != NULL); + assert(circuit_circuit_gate(circuit, gate, targets, 2, + parameterized ? arguments : NULL, + parameterized ? 1 : 0) == 0); + /* CParameter arguments are stored as parameter-table indices. + * Resolve them in the owning circuit before extracting the raw + * DAG Operation, which has no access to that parameter table. + * The gate definition still contains theta; matrix() must bind it. */ + CCircuit* resolved = circuit_assign_params(circuit, ""); + assert(resolved != NULL && circuit_num_parameters(resolved) == 0); + circuit_free(circuit); + circuit = resolved; + CCircuitDag* dag = circuit_dag_from_circuit(circuit); + assert(dag != NULL && circuit_dag_op_nodes_len(dag) == 1); + uint32_t node; + assert(circuit_dag_op_nodes(dag, &node, 1) == 0); + COperation* operation = circuit_dag_operation(dag, node); + assert(operation != NULL); + size_t rows = 0, cols = 0; + assert(operation_matrix_len(operation) == 16); + assert(operation_matrix_dims(operation, &rows, &cols) == 0); + assert(rows == 4 && cols == 4); + double local[32], full[32]; + assert(operation_matrix(operation, local, 32) == 16); + assert(circuit_to_matrix(circuit, NULL, 0, full, 32) == 16); + for (size_t row = 0; row < 4; ++row) { + for (size_t col = 0; col < 4; ++col) { + for (int local_basis = 0; local_basis < 2; ++local_basis) { + size_t flip = local_basis ? 2 : 1; + double re = 0, im = 0; + if (parameterized) { + if (row == col) re = cos(angle / 2); + if (row == (col ^ flip)) im = -sin(angle / 2); + } else if (row == (col ^ flip)) { + re = 1; + } + double expected_re = re * cos(0.13) - im * sin(0.13); + double expected_im = re * sin(0.13) + im * cos(0.13); + const double* matrix = local_basis ? local : full; + size_t index = 2 * (row * 4 + col); + assert(fabs(matrix[index] - expected_re) < 1e-12); + assert(fabs(matrix[index + 1] - expected_im) < 1e-12); + } + } + } + operation_free(operation); + circuit_dag_free(dag); + circuit_free(circuit); + param_free(argument); + } + circuit_gate_free(gate); + param_free(theta); + circuit_free(body); + } + } +} + +static void test_block_zxz(void) { + Complex64 u[64] = {0}; + for (size_t j = 0; j < 8; ++j) { + u[8 * ((j + 1) % 8) + j] = (Complex64){cos(0.37), sin(0.37)}; + } + for (uint8_t opt = 0; opt <= (BLOCK_ZXZ_OPT_ALL | BLOCK_ZXZ_OPT_A2_FORCE); ++opt) { + CCircuit* c = block_zxz_decompose(u, 8, 1e-10, opt); + assert(c != NULL); + double actual[128]; + assert(circuit_to_matrix(c, NULL, 0, actual, 128) == 64); + for (size_t i = 0; i < 64; ++i) { + assert(hypot(actual[2 * i] - u[i].re, actual[2 * i + 1] - u[i].im) <= 1e-10); + } + circuit_free(c); + } + + /* Check 1q, 2q, and 4q dimensions with non-trivial global phase. */ + size_t dims[3] = {2, 4, 16}; + for (size_t k = 0; k < 3; ++k) { + size_t dim = dims[k]; + size_t n2 = dim * dim; + Complex64* qft = (Complex64*)calloc(n2, sizeof(Complex64)); + double* actual = (double*)malloc(2 * n2 * sizeof(double)); + assert(qft != NULL && actual != NULL); + double scale = 1.0 / sqrt((double)dim); + double tau = 6.283185307179586476925286766559; + for (size_t r = 0; r < dim; ++r) { + for (size_t col = 0; col < dim; ++col) { + double ang = tau * (double)(r * col) / (double)dim + 0.51; + qft[r * dim + col] = (Complex64){scale * cos(ang), scale * sin(ang)}; + } + } + CCircuit* c = block_zxz_decompose(qft, dim, 1e-10, BLOCK_ZXZ_OPT_ALL); + assert(c != NULL); + assert(circuit_to_matrix(c, NULL, 0, actual, 2 * n2) == (int64_t)n2); + for (size_t i = 0; i < n2; ++i) { + assert(hypot(actual[2 * i] - qft[i].re, actual[2 * i + 1] - qft[i].im) <= 1e-10); + } + circuit_free(c); + free(actual); + free(qft); + } + + /* Slightly noisy input within a loose tolerance (> 1e-8) succeeds via unitary projection. */ + Complex64 noisy[64]; + for (size_t i = 0; i < 64; ++i) { + noisy[i] = (Complex64){u[i].re * (1.0 + 2e-7), u[i].im * (1.0 + 2e-7)}; + } + CCircuit* cn = block_zxz_decompose(noisy, 8, 1e-5, BLOCK_ZXZ_OPT_ALL); + assert(cn != NULL); + double actual_noisy[128]; + assert(circuit_to_matrix(cn, NULL, 0, actual_noisy, 128) == 64); + for (size_t i = 0; i < 64; ++i) { + assert(hypot(actual_noisy[2 * i] - noisy[i].re, actual_noisy[2 * i + 1] - noisy[i].im) <= + 1e-5); + } + circuit_free(cn); + + /* Exact zero and negative-zero tolerance on exact identity. */ + Complex64 eye8[64] = {0}; + for (size_t i = 0; i < 8; ++i) eye8[i * 8 + i] = (Complex64){1.0, 0.0}; + CCircuit* c0 = block_zxz_decompose(eye8, 8, 0.0, BLOCK_ZXZ_OPT_ALL); + assert(c0 != NULL); + circuit_free(c0); + CCircuit* cneg0 = block_zxz_decompose(eye8, 8, -0.0, BLOCK_ZXZ_OPT_ALL); + assert(cneg0 != NULL); + circuit_free(cneg0); + + /* Invalid inputs: null, unaligned, bad dims, overflow, unknown option bits, bad atol, + * non-finite. */ + assert(block_zxz_decompose(NULL, 8, 1e-10, 0) == NULL); + unsigned char raw[64 * sizeof(Complex64) + 16] = {0}; + uintptr_t aligned_addr = ((uintptr_t)raw + 7) & ~(uintptr_t)7; + assert(block_zxz_decompose((const Complex64*)(aligned_addr + 1), 2, 1e-10, 0) == NULL); + assert(block_zxz_decompose(u, 0, 1e-10, 0) == NULL); + assert(block_zxz_decompose(u, 1, 1e-10, 0) == NULL); + assert(block_zxz_decompose(u, 3, 1e-10, 0) == NULL); + assert(block_zxz_decompose(u, (size_t)1 << 21, 1e-10, 0) == NULL); + assert(block_zxz_decompose(u, SIZE_MAX / 2 + 1, 1e-10, 0) == NULL); + assert(block_zxz_decompose(u, (size_t)1 << (sizeof(size_t) * 4 - 1), 1e-10, 0) == NULL); + assert(block_zxz_decompose(u, 8, 1e-10, 8) == NULL); + assert(block_zxz_decompose(u, 8, 1e-10, 255) == NULL); + + /* CUnitaryDecomposeConfig exposes block_zxz_options and rejects unknown option bits. */ + CUnitaryDecomposeConfig cfg = decompose_unitary_config_default(); + assert(cfg.has_block_zxz_options == 1); + assert(cfg.block_zxz_options == BLOCK_ZXZ_OPT_ALL); + CCircuit* src3 = circuit_new(3); + assert(src3 != NULL); + uint32_t qargs3[3] = {2, 1, 0}; + assert(circuit_unitary(src3, "roll3", 3, u, qargs3, 3) == 0); + CCircuit* opt_out = decompose_unitaries(src3, cfg); + assert(opt_out != NULL); + double actual_pass[128]; + assert(circuit_to_matrix(opt_out, NULL, 0, actual_pass, 128) == 64); + for (size_t i = 0; i < 64; ++i) { + assert(hypot(actual_pass[2 * i] - u[i].re, actual_pass[2 * i + 1] - u[i].im) <= 1e-10); + } + circuit_free(opt_out); + /* Zero-initialized CUnitaryDecomposeConfig uses default Block-ZXZ options. */ + CUnitaryDecomposeConfig zero_cfg = {0}; + zero_cfg.recurse_control_flow = 1; + CCircuit* zero_out = decompose_unitaries(src3, zero_cfg); + assert(zero_out != NULL); + circuit_free(zero_out); + cfg.block_zxz_options = 0; + CCircuit* unopt_out = decompose_unitaries(src3, cfg); + assert(unopt_out != NULL); + circuit_free(unopt_out); + cfg.block_zxz_options = 8; + assert(decompose_unitaries(src3, cfg) == NULL); + circuit_free(src3); + assert(block_zxz_decompose(u, 8, NAN, 0) == NULL); + assert(block_zxz_decompose(u, 8, INFINITY, 0) == NULL); + assert(block_zxz_decompose(u, 8, -INFINITY, 0) == NULL); + assert(block_zxz_decompose(u, 8, -1e-300, 0) == NULL); + assert(block_zxz_decompose(u, 8, -1, 0) == NULL); + u[0].re = 2.0; + assert(block_zxz_decompose(u, 8, 1e-10, 0) == NULL); + u[0].re = INFINITY; + assert(block_zxz_decompose(u, 8, 1e-10, 0) == NULL); + u[0].re = 0.0; + u[0].im = NAN; + assert(block_zxz_decompose(u, 8, 1e-10, 0) == NULL); +} + int main(void) { + test_block_zxz(); test_basic_circuit(); test_errors(); test_symbolic_parameters(); test_extended_gates(); + test_circuit_gate_operation_matrix(); printf("binding-c circuit tests passed\n"); return 0; } diff --git a/crates/binding-c/tests/test_density_matrix_targets.c b/crates/binding-c/tests/test_density_matrix_targets.c new file mode 100644 index 00000000..342c8401 --- /dev/null +++ b/crates/binding-c/tests/test_density_matrix_targets.c @@ -0,0 +1,62 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// Licensed under the Apache License, Version 2.0. See LICENSE.txt or +// http://www.apache.org/licenses/LICENSE-2.0. + +#include +#include +#include +#include + +#include "cqlib_c.h" + +int main(void) { + Complex64 amplitudes[4]; + Complex64 operator[16]; + const double vector[4] = {4.0, -1.0, 2.0, 3.0}; + for (int i = 0; i < 4; ++i) { + amplitudes[i] = (Complex64){(i + 1) / sqrt(30.0), 0.0}; + for (int j = 0; j < 4; ++j) { + operator[4 * i + j] = + (Complex64){(i == j ? 1.0 : 0.0) - 2.0 * vector[i] * vector[j] / 30.0, 0.0}; + } + } + CDensityMatrix* dm = density_matrix_from_state(2, amplitudes, 4); + assert(dm != NULL); + Complex64 before[16], after[16]; + assert(density_matrix_data(dm, before, 16) == 0); + for (uint32_t q = 0; q < 2; ++q) { + const uint32_t targets[2] = {q, q}; + /* Check Kraus first: a panic must fail the host-process test. */ + assert(density_matrix_apply_kraus(dm, operator, 1, 4, targets, 2) == -8); + assert(density_matrix_data(dm, after, 16) == 0); + assert(memcmp(before, after, sizeof(before)) == 0); + assert(density_matrix_apply_cx(dm, q, q) == -8); + assert(density_matrix_apply_cz(dm, q, q) == -8); + assert(density_matrix_data(dm, after, 16) == 0); + assert(memcmp(before, after, sizeof(before)) == 0); + } + /* A valid channel must still work after the rejected operations. */ + const uint32_t targets[2] = {0, 1}; + assert(density_matrix_apply_kraus(dm, operator, 1, 4, targets, 2) == 0); + assert(density_matrix_data(dm, after, 16) == 0); + double evolved[4] = {0}; + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + evolved[i] += operator[4 * i + j].re * amplitudes[((j & 1) << 1) | (j >> 1)].re; + } + } + for (int i = 0; i < 4; ++i) { + for (int j = 0; j < 4; ++j) { + const int row = ((i & 1) << 1) | (i >> 1); + const int col = ((j & 1) << 1) | (j >> 1); + assert(fabs(after[4 * row + col].re - evolved[i] * evolved[j]) < 1e-12); + assert(fabs(after[4 * row + col].im) < 1e-12); + } + } + density_matrix_free(dm); + puts("density matrix target validation passed"); + return 0; +} diff --git a/crates/binding-c/tests/test_parity_compile_em.c b/crates/binding-c/tests/test_parity_compile_em.c index 839620ee..99cba868 100644 --- a/crates/binding-c/tests/test_parity_compile_em.c +++ b/crates/binding-c/tests/test_parity_compile_em.c @@ -64,7 +64,8 @@ static void test_copy_swap_circuit(void) { CCircuit* copy_swap = virtual_distillation_build_copy_swap_circuit(vd); assert(copy_swap != NULL); - assert(circuit_num_qubits(copy_swap) == 2); + /* copies (2) * base width (1) + 1 ancilla qubit. */ + assert(circuit_num_qubits(copy_swap) == 3); assert(circuit_num_operations(copy_swap) > 0); circuit_free(copy_swap); diff --git a/crates/binding-c/tests/test_qis_algebra.c b/crates/binding-c/tests/test_qis_algebra.c new file mode 100644 index 00000000..474f48c6 --- /dev/null +++ b/crates/binding-c/tests/test_qis_algebra.c @@ -0,0 +1,249 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +#include +#include +#include +#include +#include + +#include "cqlib_c.h" + +_Static_assert(sizeof(Complex64) == 2 * sizeof(double), "complex layout"); +_Static_assert(offsetof(Complex64, im) == sizeof(double), "complex imaginary offset"); +_Static_assert(offsetof(CFermionicLadder, kind) == sizeof(size_t), "ladder tag offset"); +_Static_assert(offsetof(CFermionicTerm, len) == sizeof(void*), "term length offset"); +_Static_assert(offsetof(CHamiltonianTerm, coefficient) == sizeof(void*), + "Pauli coefficient offset"); + +static void test_fermions(void) { + CFermionicOp *a = NULL, *c = NULL, *ac = NULL, *ca = NULL; + CFermionicOp *sum = NULL, *identity = NULL, *ordered = NULL, *copy = NULL; + CFermionicOp *number = NULL, *total = NULL, *zero = NULL, *scaled = NULL; + CFermionicOp *difference = NULL, *adjoint = NULL; + uint8_t yes = 99; + size_t n = 99; + assert(fermionic_op_annihilation(1, 0, &a) == 0); + assert(fermionic_op_creation(1, 0, &c) == 0); + assert(fermionic_op_mul(a, c, &ac) == 0); + assert(fermionic_op_mul(c, a, &ca) == 0); + assert(fermionic_op_add(ac, ca, &sum) == 0); + assert(fermionic_op_identity(1, &identity) == 0); + assert(fermionic_op_equiv(sum, identity, 0, &yes) == 0 && yes == 1); + assert(fermionic_op_equals(sum, identity, &yes) == 0 && yes == 0); + assert(fermionic_op_normal_order(sum, &ordered) == 0); + assert(fermionic_op_equals(ordered, identity, &yes) == 0 && yes == 1); + assert(fermionic_op_num_modes(c, &n) == 0 && n == 1); + assert(fermionic_op_num_terms(c, &n) == 0 && n == 1); + assert(fermionic_op_term_len(c, 0, &n) == 0 && n == 1); + CFermionicLadder buffer[2] = {{99, 99}, {99, 99}}; + Complex64 coefficient = {99, 99}; + assert(fermionic_op_get_term(c, 0, buffer, 0, &coefficient) == -8); + assert(buffer[0].mode == 99 && coefficient.re == 99); + assert(fermionic_op_get_term(c, 0, buffer, 2, &coefficient) == 0); + assert(buffer[0].mode == 0 && buffer[0].kind == FERMIONIC_CREATE); + assert(buffer[1].mode == 99); + assert(fermionic_op_copy(c, ©) == 0); + assert(fermionic_op_chop(copy, 1) == 0); + assert(fermionic_op_is_zero(copy, &yes) == 0 && yes == 1); + assert(fermionic_op_number(1, 0, &number) == 0); + assert(fermionic_op_total_number(1, &total) == 0); + assert(fermionic_op_equiv(number, total, 0, &yes) == 0 && yes == 1); + assert(fermionic_op_new(1, &zero) == 0); + assert(fermionic_op_scaled(c, (Complex64){1e-20, 0}, &scaled) == 0); + assert(fermionic_op_num_terms(scaled, &n) == 0 && n == 1); + assert(fermionic_op_sub(c, c, &difference) == 0); + assert(fermionic_op_equiv(difference, zero, 0, &yes) == 0 && yes == 1); + assert(fermionic_op_adjoint(a, &adjoint) == 0); + assert(fermionic_op_equals(adjoint, c, &yes) == 0 && yes == 1); + assert(fermionic_op_is_hermitian(number, 0, &yes) == 0 && yes == 1); + CFermionicLadder creator = {0, FERMIONIC_CREATE}; + CFermionicTerm terms[] = {{&creator, 1, {1, 0}}, {&creator, 1, {2, 0}}}; + CFermionicOp *batch = NULL, *single = NULL; + assert(fermionic_op_from_terms(1, terms, 2, &batch) == 0); + assert(fermionic_op_from_term(1, &creator, 1, (Complex64){3, 0}, &single) == 0); + assert(fermionic_op_equiv(batch, single, 0, &yes) == 0 && yes == 1); + assert(fermionic_op_add_term(batch, &creator, 1, (Complex64){-3, 0}) == 0); + assert(fermionic_op_is_zero(batch, &yes) == 0 && yes == 1); + CFermionicOp* out = c; + assert(fermionic_op_creation(1, 1, &out) == -2 && out == c); + creator.kind = 255; + assert(fermionic_op_from_term(1, &creator, 1, (Complex64){0, 0}, &out) == -8 && out == c); + assert(fermionic_op_scaled(c, (Complex64){NAN, 0}, &out) == -8 && out == c); + assert(fermionic_op_chop(c, -1) == -8); + assert(fermionic_op_equals(c, adjoint, &yes) == 0 && yes == 1); + fermionic_op_free(batch); + fermionic_op_free(single); + fermionic_op_free(a); + fermionic_op_free(c); + fermionic_op_free(ac); + fermionic_op_free(ca); + fermionic_op_free(sum); + fermionic_op_free(identity); + fermionic_op_free(ordered); + fermionic_op_free(copy); + fermionic_op_free(number); + fermionic_op_free(total); + fermionic_op_free(zero); + fermionic_op_free(scaled); + fermionic_op_free(difference); + fermionic_op_free(adjoint); + fermionic_op_free(NULL); +} + +static void test_pauli_algebra(void) { + CPauliString *px = pauli_string_parse("X"), *pz = pauli_string_parse("Z"); + CPauliString *py = pauli_string_parse("Y"), *pxz = pauli_string_parse("XZ"); + assert(px && pz && py && pxz); + CHamiltonianTerm tx = {px, {1, 0}}, tz = {pz, {1, 0}}; + CHamiltonianTerm ty = {py, {0, -1}}, txz = {pxz, {1, 0}}; + CHamiltonian *x = NULL, *z = NULL, *y = NULL, *expected = NULL; + CHamiltonian *product = NULL, *tensor = NULL, *sum = NULL, *difference = NULL; + CHamiltonian *adjoint = NULL, *scaled = NULL, *copy = NULL, *normalized = NULL; + CHamiltonian *hermitian = NULL, *remapped = NULL, *identity = NULL; + uint8_t yes = 99; + assert(hamiltonian_from_terms(1, &tx, 1, &x) == 0); + assert(hamiltonian_from_terms(1, &tz, 1, &z) == 0); + assert(hamiltonian_from_terms(1, &ty, 1, &y) == 0); + assert(hamiltonian_from_terms(2, &txz, 1, &expected) == 0); + pauli_string_free(px); + pauli_string_free(pz); + pauli_string_free(py); + pauli_string_free(pxz); + assert(hamiltonian_mul(x, z, &product) == 0); + assert(hamiltonian_equiv(product, y, 0, &yes) == 0 && yes == 1); + assert(hamiltonian_tensor(x, z, &tensor) == 0); + assert(hamiltonian_equiv(tensor, expected, 0, &yes) == 0 && yes == 1); + assert(hamiltonian_add(x, z, &sum) == 0); + assert(hamiltonian_sub(sum, z, &difference) == 0); + assert(hamiltonian_equiv(difference, x, 0, &yes) == 0 && yes == 1); + assert(hamiltonian_adjoint(product, &adjoint) == 0); + assert(hamiltonian_scaled(product, (Complex64){-1, 0}, &scaled) == 0); + assert(hamiltonian_equiv(adjoint, scaled, 0, &yes) == 0 && yes == 1); + assert(hamiltonian_copy(x, ©) == 0); + assert(hamiltonian_chop(copy, 1) == 0 && hamiltonian_num_terms(copy) == 0); + assert(hamiltonian_num_terms(x) == 1); + assert(hamiltonian_normalized(x, &normalized) == 0); + assert(hamiltonian_normalized_hermitian(x, &hermitian) == 0); + assert(hamiltonian_is_hermitian(product, 0, &yes) == 0 && yes == 0); + assert(hamiltonian_is_hermitian(hermitian, 0, &yes) == 0 && yes == 1); + const size_t mapping[] = {1}; + assert(hamiltonian_remap_qubits(x, mapping, 1, 2, &remapped) == 0); + assert(hamiltonian_identity(0, &identity) == 0); + CPauliString* snapshot = NULL; + Complex64 coefficient = {99, 99}; + assert(hamiltonian_get_term(identity, 0, &snapshot, &coefficient) == 0); + hamiltonian_free(identity); + assert(pauli_string_num_qubits(snapshot) == 0 && coefficient.re == 1); + pauli_string_free(snapshot); + CHamiltonian* out = x; + assert(hamiltonian_add(x, tensor, &out) == -8 && out == x); + assert(hamiltonian_normalized_hermitian(product, &out) == -8 && out == x); + assert(hamiltonian_identity(SIZE_MAX, &out) == -7 && out == x); + assert(hamiltonian_equiv(x, z, NAN, &yes) == -8 && yes == 1); + hamiltonian_free(x); + hamiltonian_free(z); + hamiltonian_free(y); + hamiltonian_free(expected); + hamiltonian_free(product); + hamiltonian_free(tensor); + hamiltonian_free(sum); + hamiltonian_free(difference); + hamiltonian_free(adjoint); + hamiltonian_free(scaled); + hamiltonian_free(copy); + hamiltonian_free(normalized); + hamiltonian_free(hermitian); + hamiltonian_free(remapped); +} + +static void test_mapping_and_evolution(void) { + size_t sources[] = {0}, targets[] = {1}, width = 99; + CFermionicOp* generator = NULL; + CHamiltonian* mapped = NULL; + assert(fermionic_op_excitation_generator(2, sources, 1, targets, 1, &generator) == 0); + assert(jordan_wigner_num_qubits(2, &width) == 0 && width == 2); + assert(jordan_wigner_map_operator(generator, &mapped) == 0); + uint8_t occupation[] = {1, 0}, bits[] = {99, 99}; + assert(jordan_wigner_map_occupation(occupation, 2, bits, 2) == 0 && bits[0] == 1 && + bits[1] == 0); + occupation[1] = 2; + assert(jordan_wigner_map_occupation(occupation, 2, bits, 2) == -8 && bits[0] == 1 && + bits[1] == 0); + assert(jordan_wigner_map_occupation(NULL, 0, NULL, 0) == 0); + const double theta = 0.37; + CCircuit* evolution = + hamiltonian_to_evolution_circuit(mapped, theta, 1, TROTTER_MODE_SECOND_ORDER); + assert(evolution); + Complex64 state[] = {{0, 0}, {1, 0}, {0, 0}, {0, 0}}, data[4]; + CStatevector* sv = statevector_from_state(2, state, 4); + assert(sv); + assert(statevector_apply_circuit(sv, evolution) == 0); + assert(statevector_data(sv, data, 4) == 0); + assert(fabs(data[1].re - cos(theta)) < 1e-12 && fabs(data[1].im) < 1e-12); + assert(fabs(data[2].re - sin(theta)) < 1e-12 && fabs(data[2].im) < 1e-12); + assert(hypot(data[0].re, data[0].im) < 1e-12 && hypot(data[3].re, data[3].im) < 1e-12); + statevector_free(sv); + circuit_free(evolution); + hamiltonian_free(mapped); + fermionic_op_free(generator); + CCircuit* phase = circuit_new(1); + assert(circuit_set_global_phase(phase, theta) == 0); + sv = statevector_from_circuit(phase); + assert(sv && statevector_data(sv, data, 2) == 0); + assert(fabs(data[0].re - cos(theta)) < 1e-12 && fabs(data[0].im - sin(theta)) < 1e-12); + statevector_free(sv); + circuit_free(phase); +} + +static void test_wide_sparse_registers(void) { + const size_t bits = sizeof(size_t) * CHAR_BIT; + const size_t widths[] = {bits, bits + 1, bits - 1, bits / 2, bits / 2 - 1, bits / 2 - 2}; + for (size_t i = 0; i < sizeof(widths) / sizeof(widths[0]); ++i) { + CFermionicOp* identity = NULL; + CHamiltonian* mapped = NULL; + CPauliString* pauli = NULL; + Complex64 coefficient = {0, 0}, buffer = {99, -99}; + assert(fermionic_op_identity(widths[i], &identity) == 0); + assert(jordan_wigner_map_operator(identity, &mapped) == 0); + assert(hamiltonian_get_term(mapped, 0, &pauli, &coefficient) == 0); + const size_t dim = widths[i] < bits ? (size_t)1 << widths[i] : 0; + assert(hamiltonian_to_matrix_len(mapped) == dim); + assert(pauli_string_matrix_len(pauli) == dim); + assert(hamiltonian_to_matrix(mapped, &buffer, 1) == -7); + assert(buffer.re == 99 && buffer.im == -99); + assert(pauli_string_matrix(pauli, &buffer, 1) == -7); + assert(buffer.re == 99 && buffer.im == -99); + pauli_string_free(pauli); + hamiltonian_free(mapped); + fermionic_op_free(identity); + } + CFermionicOp* zero = NULL; + CHamiltonian* mapped = NULL; + assert(fermionic_op_new(SIZE_MAX, &zero) == 0); + assert(jordan_wigner_map_operator(zero, &mapped) == 0); + assert(hamiltonian_to_matrix_len(mapped) == 0); + Complex64 buffer = {99, -99}; + assert(hamiltonian_to_matrix(mapped, &buffer, 1) == -7); + assert(buffer.re == 99 && buffer.im == -99); + hamiltonian_free(mapped); + fermionic_op_free(zero); +} + +int main(void) { + test_fermions(); + test_pauli_algebra(); + test_mapping_and_evolution(); + test_wide_sparse_registers(); + puts("binding-c checked algebra tests passed"); + return 0; +} diff --git a/crates/binding-python/Cargo.toml b/crates/binding-python/Cargo.toml index 0e8c4838..29ab69ac 100644 --- a/crates/binding-python/Cargo.toml +++ b/crates/binding-python/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "binding-python" -version = "2.0.0-beta1" +version = "2.0.0-beta7" edition.workspace = true rust-version.workspace = true license-file.workspace = true @@ -12,9 +12,9 @@ name = "_native" crate-type = ["cdylib", "rlib"] [dependencies] -pyo3 = { version = "0.29", features = ["abi3-py310", "num-complex", "chrono"] } +pyo3 = { version = "0.29", features = ["abi3-py311", "num-complex", "chrono"] } chrono = "0.4" -cqlib-core = { path = "../cqlib-core", version = '0.1.0-beta.1' } +cqlib-core = { path = "../cqlib-core", version = '0.1.0-beta.7' } num-complex.workspace = true numpy.workspace = true rustworkx-core.workspace = true diff --git a/crates/binding-python/README.md b/crates/binding-python/README.md index d9c4e507..9062b64d 100644 --- a/crates/binding-python/README.md +++ b/crates/binding-python/README.md @@ -10,7 +10,7 @@ mitigation, and visualization. ## Installation -Cqlib requires Python 3.10 or later. +Cqlib requires Python 3.11 or later. Install the latest pre-release from PyPI: @@ -50,7 +50,7 @@ bound = circuit.assign_parameters({"theta": 0.5}) ## Supported environments -- Python 3.10 or later on CPython +- CPython 3.11–3.15 with the GIL enabled - Linux, macOS, and Windows - Type information is included for static type checkers diff --git a/crates/binding-python/cqlib/circuit/__init__.py b/crates/binding-python/cqlib/circuit/__init__.py index 9c07cc62..b75bda5d 100644 --- a/crates/binding-python/cqlib/circuit/__init__.py +++ b/crates/binding-python/cqlib/circuit/__init__.py @@ -49,6 +49,7 @@ ClassicalValue = _circuit_module.ClassicalValue Measurement = _circuit_module.Measurement ClassicalExpr = _circuit_module.ClassicalExpr +ClassicalDataOp = _circuit_module.ClassicalDataOp ValueControlBody = _circuit_module.ValueControlBody ValueSwitchCase = _circuit_module.ValueSwitchCase ClassicalControlOp = _circuit_module.ClassicalControlOp @@ -66,6 +67,7 @@ "CircuitId", "CircuitError", "ClassicalControlOp", + "ClassicalDataOp", "ClassicalExpr", "ClassicalType", "ClassicalValue", diff --git a/crates/binding-python/cqlib/circuit/__init__.pyi b/crates/binding-python/cqlib/circuit/__init__.pyi index 137a02ca..5eb8918a 100644 --- a/crates/binding-python/cqlib/circuit/__init__.pyi +++ b/crates/binding-python/cqlib/circuit/__init__.pyi @@ -57,6 +57,7 @@ Submodule Purpose Key types ``.gates`` Gate definitions and factory constants :class:`StandardGate` ``.parameter`` Symbolic/numeric parameter expressions :class:`Parameter` ``.classical`` Runtime classical types and storage handles :class:`ClassicalType` +``.classical_data`` Runtime classical data operations :class:`ClassicalDataOp` ``.classical_expr`` Typed classical expression AST :class:`ClassicalExpr` ``.control_flow`` Classical control-flow operations :class:`ClassicalControlOp` ``.operation`` Instruction and operation types :class:`ValueOperation` @@ -84,6 +85,7 @@ from .classical import ( ClassicalVar as ClassicalVar, Measurement as Measurement, ) +from .classical_data import ClassicalDataOp as ClassicalDataOp from .classical_expr import ClassicalExpr as ClassicalExpr from .control_flow import ( ClassicalControlOp as ClassicalControlOp, @@ -121,6 +123,7 @@ __all__ = [ "CircuitId", "CircuitError", "ClassicalControlOp", + "ClassicalDataOp", "ClassicalExpr", "ClassicalType", "ClassicalValue", diff --git a/crates/binding-python/cqlib/circuit/ansatz/hamiltonian_evolution.pyi b/crates/binding-python/cqlib/circuit/ansatz/hamiltonian_evolution.pyi index c68ff21c..a64c9cc4 100644 --- a/crates/binding-python/cqlib/circuit/ansatz/hamiltonian_evolution.pyi +++ b/crates/binding-python/cqlib/circuit/ansatz/hamiltonian_evolution.pyi @@ -331,9 +331,10 @@ class PauliEvolutionAnsatz: def __init__(self, hamiltonian: Hamiltonian) -> None: """Creates a new ``PauliEvolutionAnsatz``. - The Hamiltonian is automatically **simplified** before processing: - Pauli phases are absorbed into coefficients, duplicate terms are merged, - and near-zero terms are removed. The default strategy is + The Hamiltonian is normalized before processing: Pauli phases are absorbed, + duplicate terms are merged, and imaginary residuals of magnitude <= 1e-10 + are projected to zero. Larger imaginary parts are rejected; every nonzero + real coefficient is retained. The default strategy is :meth:`EvolutionStrategy.auto` with ``steps=1``. Args: diff --git a/crates/binding-python/cqlib/circuit/circuit.pyi b/crates/binding-python/cqlib/circuit/circuit.pyi index 316e3338..94fab82b 100644 --- a/crates/binding-python/cqlib/circuit/circuit.pyi +++ b/crates/binding-python/cqlib/circuit/circuit.pyi @@ -638,7 +638,15 @@ class Circuit: """ ... def compose(self, other: Circuit, qubits: QubitList | None = ...) -> None: - """Append another circuit, optionally remapping its qubits.""" + """Append another circuit, optionally remapping its qubits in insertion order. + + Explicit targets must be distinct and already present in this circuit. + If ``qubits`` is None, merge qubits by ID, appending previously absent IDs. + Errors leave this circuit unchanged; existing classical handles remain valid. + + Raises: + CircuitError: If the mapping is invalid or stored references cannot be remapped. + """ ... def to_matrix(self, qubits_order: list[int] | None = ...) -> NDArray[np.complex128]: """Compute the dense numeric unitary matrix. diff --git a/crates/binding-python/cqlib/circuit/classical_data.py b/crates/binding-python/cqlib/circuit/classical_data.py new file mode 100644 index 00000000..64c27fde --- /dev/null +++ b/crates/binding-python/cqlib/circuit/classical_data.py @@ -0,0 +1,19 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Runtime exports for classical data operations.""" + +from .._native import circuit as _circuit_module + +ClassicalDataOp = _circuit_module.ClassicalDataOp + +__all__ = ["ClassicalDataOp"] diff --git a/crates/binding-python/cqlib/circuit/classical_data.pyi b/crates/binding-python/cqlib/circuit/classical_data.pyi new file mode 100644 index 00000000..1c389662 --- /dev/null +++ b/crates/binding-python/cqlib/circuit/classical_data.pyi @@ -0,0 +1,46 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Runtime classical data operations. + +:class:`ClassicalDataOp` models side-effecting classical updates in a +circuit schedule: stores into mutable classical variables and measurements +producing immutable classical values. Instances are obtained from +:attr:`Instruction.classical_data` or :attr:`ValueInstruction.classical_data`; +they are not constructed directly. +""" + +from .classical import ClassicalValue, ClassicalVar +from .classical_expr import ClassicalExpr + +class ClassicalDataOp: + """Runtime classical data operation (store or measurement).""" + @property + def kind(self) -> str: + """One of ``"store"``, ``"measure_bit"``, or ``"measure_bits"``.""" + ... + @property + def target(self) -> ClassicalVar | None: + """The store target variable if this is a store operation.""" + ... + @property + def value(self) -> ClassicalExpr | None: + """The stored expression if this is a store operation.""" + ... + @property + def result(self) -> ClassicalValue | None: + """The immutable value receiving the result if this is a measurement.""" + ... + def __eq__(self, other: object) -> bool: ... + def __copy__(self) -> ClassicalDataOp: ... + def __deepcopy__(self, memo: dict) -> ClassicalDataOp: ... + def __repr__(self) -> str: ... diff --git a/crates/binding-python/cqlib/circuit/operation.pyi b/crates/binding-python/cqlib/circuit/operation.pyi index d422a7a6..0e541f29 100644 --- a/crates/binding-python/cqlib/circuit/operation.pyi +++ b/crates/binding-python/cqlib/circuit/operation.pyi @@ -21,6 +21,7 @@ qubits and parameters to form a complete circuit operation. import numpy as np from numpy.typing import NDArray from .bit import Qubit +from .classical_data import ClassicalDataOp from .control_flow import ClassicalControlOp from .gates import CircuitGate, Directive, MCGate, StandardGate, UnitaryGate from .parameter import Parameter @@ -99,6 +100,34 @@ class Instruction: def directive(self) -> Directive | None: """The :class:`Directive` if this is a directive instruction.""" ... + @property + def mc_gate(self) -> MCGate | None: + """The :class:`MCGate` if this is an mc-gate instruction. + + The returned gate carries no bound parameters: parameters belong to + the operation (``Operation.params`` / ``ValueOperation.params``), not + to the instruction. + """ + ... + @property + def unitary_gate(self) -> UnitaryGate | None: + """The :class:`UnitaryGate` if this is a unitary instruction. + + Parameters of a parametric unitary belong to the operation, not to + the instruction. + """ + ... + @property + def circuit_gate(self) -> CircuitGate | None: + """The :class:`CircuitGate` if this is a circuit-gate instruction. + + Parameters belong to the operation, not to the instruction. + """ + ... + @property + def classical_data(self) -> ClassicalDataOp | None: + """The :class:`ClassicalDataOp` if this is a classical-data instruction.""" + ... def __str__(self) -> str: ... def __copy__(self) -> Instruction: ... def __deepcopy__(self, memo: dict) -> Instruction: ... @@ -153,6 +182,33 @@ class ValueInstruction: """The :class:`Directive` if this is a directive instruction.""" ... @property + def mc_gate(self) -> MCGate | None: + """The :class:`MCGate` if this is an mc-gate instruction. + + The returned gate carries no bound parameters: parameters belong to + the operation (``ValueOperation.params``), not to the instruction. + """ + ... + @property + def unitary_gate(self) -> UnitaryGate | None: + """The :class:`UnitaryGate` if this is a unitary instruction. + + Parameters of a parametric unitary belong to the operation, not to + the instruction. + """ + ... + @property + def circuit_gate(self) -> CircuitGate | None: + """The :class:`CircuitGate` if this is a circuit-gate instruction. + + Parameters belong to the operation, not to the instruction. + """ + ... + @property + def classical_data(self) -> ClassicalDataOp | None: + """The :class:`ClassicalDataOp` if this is a classical-data instruction.""" + ... + @property def instruction(self) -> Instruction | None: """The inner :class:`Instruction` when this is a plain instruction.""" ... diff --git a/crates/binding-python/cqlib/circuit/parameter.pyi b/crates/binding-python/cqlib/circuit/parameter.pyi index 3e67a27d..fd7a8be4 100644 --- a/crates/binding-python/cqlib/circuit/parameter.pyi +++ b/crates/binding-python/cqlib/circuit/parameter.pyi @@ -123,7 +123,10 @@ class Parameter: ... def substitute(self, bindings: dict[str, Parameter]) -> Parameter: - """Substitute multiple symbols and simplify the resulting expression.""" + """Substitute simultaneously and simplify, without revisiting replacements. + + The original parameter is unchanged. + """ ... def provably_equal(self, other: Parameter, tolerance: float = 1e-12) -> bool: diff --git a/crates/binding-python/cqlib/compile/transform/decompose/__init__.py b/crates/binding-python/cqlib/compile/transform/decompose/__init__.py index 779d2cde..b23d05ce 100644 --- a/crates/binding-python/cqlib/compile/transform/decompose/__init__.py +++ b/crates/binding-python/cqlib/compile/transform/decompose/__init__.py @@ -29,8 +29,14 @@ """ from ...._native import compile as _compile_module +from . import block_zxz as block_zxz from . import mc_gate as mc_gate from . import unitary as unitary +from .block_zxz import ( + BlockZxzDecomposeOptions, + decompose_block_zxz, + decompose_block_zxz_with_options, +) _decompose_module = _compile_module.transform.decompose @@ -50,6 +56,10 @@ decompose_mc_gates_for_device = _decompose_module.decompose_mc_gates_for_device __all__ = [ + "block_zxz", + "BlockZxzDecomposeOptions", + "decompose_block_zxz", + "decompose_block_zxz_with_options", "mc_gate", "unitary", "TwoQubitUnitaryDecomposeBasis", diff --git a/crates/binding-python/cqlib/compile/transform/decompose/__init__.pyi b/crates/binding-python/cqlib/compile/transform/decompose/__init__.pyi index b0ead856..e2f17fe2 100644 --- a/crates/binding-python/cqlib/compile/transform/decompose/__init__.pyi +++ b/crates/binding-python/cqlib/compile/transform/decompose/__init__.pyi @@ -14,8 +14,14 @@ from cqlib.circuit import Circuit, Instruction from cqlib.compile.resource import ResourceLimits, ResourcePolicy from cqlib.device import Device from .. import TransformResult +from . import block_zxz as block_zxz from . import mc_gate as mc_gate from . import unitary as unitary +from .block_zxz import ( + BlockZxzDecomposeOptions, + decompose_block_zxz, + decompose_block_zxz_with_options, +) class TwoQubitUnitaryDecomposeBasis: """Output interaction basis for numeric two-qubit unitary synthesis.""" @@ -56,6 +62,7 @@ class UnitaryDecomposeConfig: two_qubit_basis: TwoQubitUnitaryDecomposeBasis | None = None, target_basis: list[Instruction | str] | None = None, recurse_control_flow: bool = True, + block_zxz_options: BlockZxzDecomposeOptions | None = None, ) -> None: ... @property def two_qubit_basis(self) -> TwoQubitUnitaryDecomposeBasis | None: @@ -77,6 +84,10 @@ class UnitaryDecomposeConfig: def recurse_control_flow(self) -> bool: """Whether unitary gates in control-flow bodies are synthesized.""" ... + @property + def block_zxz_options(self) -> BlockZxzDecomposeOptions: + """Optimization switches for three-or-more-qubit Block-ZXZ synthesis.""" + ... def __copy__(self) -> UnitaryDecomposeConfig: ... def __deepcopy__(self, memo: dict[int, object]) -> UnitaryDecomposeConfig: ... def __eq__(self, other: object) -> bool: ... @@ -135,7 +146,7 @@ def decompose_unitaries( circuit: Circuit, config: UnitaryDecomposeConfig | None = None, ) -> TransformResult: - """Synthesize matrix-backed one- and two-qubit unitary gates. + """Synthesize matrix-backed numeric unitary gates. Raises: CompilerConfigError: If a unitary is unresolved, invalid, or @@ -186,6 +197,10 @@ def decompose_mc_gates_for_device( ... __all__ = [ + "block_zxz", + "BlockZxzDecomposeOptions", + "decompose_block_zxz", + "decompose_block_zxz_with_options", "mc_gate", "unitary", "TwoQubitUnitaryDecomposeBasis", diff --git a/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.py b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.py new file mode 100644 index 00000000..ba033739 --- /dev/null +++ b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.py @@ -0,0 +1,26 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Recursive Block-ZXZ synthesis of finite numeric unitary matrices.""" + +from ...._native import compile as _compile + +_module = _compile.transform.decompose.block_zxz +BlockZxzDecomposeOptions = _module.BlockZxzDecomposeOptions +decompose_block_zxz = _module.decompose_block_zxz +decompose_block_zxz_with_options = _module.decompose_block_zxz_with_options + +__all__ = [ + "BlockZxzDecomposeOptions", + "decompose_block_zxz", + "decompose_block_zxz_with_options", +] diff --git a/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi new file mode 100644 index 00000000..dd80dc0f --- /dev/null +++ b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi @@ -0,0 +1,40 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +from numpy.typing import ArrayLike + +from cqlib.circuit import Circuit + +class BlockZxzDecomposeOptions: + def __init__( + self, *, opt_a1: bool = True, opt_a2: bool = True, opt_a2_force: bool = False + ) -> None: ... + @property + def opt_a1(self) -> bool: ... + @property + def opt_a2(self) -> bool: ... + @property + def opt_a2_force(self) -> bool: ... + @staticmethod + def none() -> BlockZxzDecomposeOptions: ... + def __copy__(self) -> BlockZxzDecomposeOptions: ... + def __deepcopy__(self, memo: dict[int, object]) -> BlockZxzDecomposeOptions: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + +def decompose_block_zxz(matrix: ArrayLike, atol: float = 1e-10) -> Circuit: ... +def decompose_block_zxz_with_options( + matrix: ArrayLike, + atol: float = 1e-10, + *, + options: BlockZxzDecomposeOptions | None = None, +) -> Circuit: ... diff --git a/crates/binding-python/cqlib/error_mitigation/virtual_distillation.py b/crates/binding-python/cqlib/error_mitigation/virtual_distillation.py index 133298d6..fb76d106 100644 --- a/crates/binding-python/cqlib/error_mitigation/virtual_distillation.py +++ b/crates/binding-python/cqlib/error_mitigation/virtual_distillation.py @@ -12,8 +12,13 @@ """Virtual distillation bindings. -Virtual distillation builds copy-swap circuits from a base circuit and combines -numerator and denominator estimates into a mitigated expectation value. +Virtual distillation builds Hadamard-test copy-swap circuits from a base +circuit: ``copies`` disjoint copies of the base circuit, a Hadamard gate on a +trailing ancillary qubit, and a ladder of ancilla-controlled SWAP gates +between adjacent copies. Numerator and denominator estimates are combined +into a mitigated expectation value; both estimator calls receive a +``Hamiltonian`` observable (the denominator observable is a single X on the +ancillary qubit). """ from collections.abc import Callable @@ -23,6 +28,12 @@ from .._native import error_mitigation as _error_mitigation_module +# Estimators receive the (widened) circuit, an optional Hamiltonian, and an +# optional shot count, and return ``(mean, variance)``. Virtual distillation +# passes a Hamiltonian on both the numerator call (the observable expanded +# with X on the ancillary qubit) and the denominator call (a single X on the +# ancillary qubit); distinguish the two by observable content, not by +# ``observable is None``. Estimator = Callable[[Circuit, Hamiltonian | None, int | None], tuple[float, float]] VirtualDistillationConfig = _error_mitigation_module.VirtualDistillationConfig VirtualDistillation = _error_mitigation_module.VirtualDistillation diff --git a/crates/binding-python/cqlib/error_mitigation/virtual_distillation.pyi b/crates/binding-python/cqlib/error_mitigation/virtual_distillation.pyi index 84921c33..7cf66c63 100644 --- a/crates/binding-python/cqlib/error_mitigation/virtual_distillation.pyi +++ b/crates/binding-python/cqlib/error_mitigation/virtual_distillation.pyi @@ -17,6 +17,12 @@ from collections.abc import Callable from cqlib.circuit import Circuit from cqlib.qis import Hamiltonian +# Estimators receive the (widened) circuit, an optional Hamiltonian, and an +# optional shot count, and return ``(mean, variance)``. Virtual distillation +# passes a Hamiltonian on both the numerator call (the observable expanded +# with X on the ancillary qubit) and the denominator call (a single X on the +# ancillary qubit); distinguish the two by observable content, not by +# ``observable is None``. Estimator = Callable[[Circuit, Hamiltonian | None, int | None], tuple[float, float]] class VirtualDistillationConfig: @@ -40,8 +46,10 @@ class VirtualDistillationConfig: class VirtualDistillation: """Low-level virtual distillation helper. - The helper builds copy-swap circuits and combines numerator and denominator - estimator outputs into a mitigated expectation value and variance. + The helper builds Hadamard-test copy-swap circuits and combines numerator + and denominator estimator outputs into a mitigated expectation value and + variance. Both estimator calls receive a ``Hamiltonian`` observable; the + denominator observable is a single X on the ancillary (last) qubit. """ def __init__(self, circuit: Circuit, copies: int) -> None: @@ -55,14 +63,27 @@ class VirtualDistillation: """Update the configured number of copies.""" ... def build_copy_swap_circuit(self) -> Circuit: - """Build the copy-swap circuit used by virtual distillation.""" + """Build the Hadamard-test copy-swap circuit used by virtual distillation. + + The returned circuit has width ``copies * base_width + 1``, where the + last qubit is the ancillary qubit. It contains, in order: the + ``copies`` copies of the base circuit, a Hadamard gate on the + ancillary qubit, and ``(copies - 1) * base_width`` ancilla-controlled + SWAP gates (exposed as ``C1-SWAP``) forming a permutation ladder + between adjacent copies. + """ ... def run_denominator_circuit( self, shots: int, estimator: Estimator, ) -> tuple[float, float]: - """Run the denominator circuit and return ``(mean, variance)``.""" + """Run the denominator circuit and return ``(mean, variance)``. + + ``estimator`` receives the copy-swap circuit together with the + denominator observable: a single X on the ancillary (last) qubit and + identity on every other qubit. + """ ... def run_numerator_circuit( self, @@ -70,7 +91,13 @@ class VirtualDistillation: shots: int, estimator: Estimator, ) -> tuple[float, float]: - """Run the numerator circuit and return ``(mean, variance)``.""" + """Run the numerator circuit and return ``(mean, variance)``. + + ``estimator`` receives the copy-swap circuit together with + ``hamiltonian`` expanded to the full circuit width: the original + Pauli terms on the first copy's qubits, identity on the remaining + copies, and X on the ancillary (last) qubit. + """ ... def run_vd( self, @@ -79,7 +106,11 @@ class VirtualDistillation: shots_denominator: int, estimator: Estimator, ) -> tuple[float, float]: - """Run virtual distillation and return ``(mitigated_mean, variance)``.""" + """Run virtual distillation and return ``(mitigated_mean, variance)``. + + The mitigated mean is the numerator estimate divided by the + denominator estimate. + """ ... def __repr__(self) -> str: ... def __copy__(self) -> VirtualDistillation: ... diff --git a/crates/binding-python/cqlib/qis/__init__.py b/crates/binding-python/cqlib/qis/__init__.py index 37eff524..bcadae72 100644 --- a/crates/binding-python/cqlib/qis/__init__.py +++ b/crates/binding-python/cqlib/qis/__init__.py @@ -65,6 +65,15 @@ # Hamiltonian module from .hamiltonian import Hamiltonian as Hamiltonian +from . import fermion as fermion +from .fermion import ( + FermionicLadder as FermionicLadder, + FermionicOp as FermionicOp, + FermionToQubitMapper as FermionToQubitMapper, + OccupationStateMapper as OccupationStateMapper, + JordanWignerMapper as JordanWignerMapper, +) + # Evolution module from .evolution import TrotterMode as TrotterMode @@ -103,6 +112,12 @@ def num_qubits(self) -> int: ... "Pauli", "PauliString", "Hamiltonian", + "fermion", + "FermionicLadder", + "FermionicOp", + "FermionToQubitMapper", + "OccupationStateMapper", + "JordanWignerMapper", "TrotterMode", "state", "Statevector", diff --git a/crates/binding-python/cqlib/qis/__init__.pyi b/crates/binding-python/cqlib/qis/__init__.pyi index fb4dbe49..e3df9927 100644 --- a/crates/binding-python/cqlib/qis/__init__.pyi +++ b/crates/binding-python/cqlib/qis/__init__.pyi @@ -33,6 +33,15 @@ from .pauli import PauliString as PauliString # Hamiltonian module from .hamiltonian import Hamiltonian as Hamiltonian +from . import fermion as fermion +from .fermion import ( + FermionicLadder as FermionicLadder, + FermionicOp as FermionicOp, + FermionToQubitMapper as FermionToQubitMapper, + OccupationStateMapper as OccupationStateMapper, + JordanWignerMapper as JordanWignerMapper, +) + # Evolution module from .evolution import TrotterMode as TrotterMode @@ -83,6 +92,12 @@ __all__ = [ "Pauli", "PauliString", "Hamiltonian", + "fermion", + "FermionicLadder", + "FermionicOp", + "FermionToQubitMapper", + "OccupationStateMapper", + "JordanWignerMapper", "TrotterMode", "state", "Statevector", diff --git a/crates/binding-python/cqlib/qis/entropy.pyi b/crates/binding-python/cqlib/qis/entropy.pyi index 2c21df18..3dc1d1ae 100644 --- a/crates/binding-python/cqlib/qis/entropy.pyi +++ b/crates/binding-python/cqlib/qis/entropy.pyi @@ -38,8 +38,9 @@ def renyi_entropy(dm: DensityMatrix, alpha: float) -> float: The Rényi entropy is defined as :math:`S_\\alpha(\\rho) = \\frac{1}{1-\\alpha} \\log_2(\\text{Tr}(\\rho^\\alpha))`. Special cases: - - When ``alpha -> 1``: Approaches Von Neumann entropy. + - When ``alpha = 1``: Returns Von Neumann entropy. - When ``alpha = 2``: Collision entropy. + - When ``alpha = +inf``: Min-entropy. Args: dm (DensityMatrix): The density matrix representing the quantum state. @@ -49,7 +50,13 @@ def renyi_entropy(dm: DensityMatrix, alpha: float) -> float: float: The Rényi entropy in bits (base-2 logarithm). Raises: - ValueError: If `alpha <= 0` or if eigendecomposition fails. + ValueError: If alpha is NaN or <= 0, eigendecomposition fails, + or no positive spectrum remains. + + Notes: + Non-diagonal spectra discard eigenvalues at or below + dimension * machine epsilon * largest eigenvalue as numerical zeros. + Diagonal spectra retain all positive entries. """ ... diff --git a/crates/binding-python/cqlib/qis/fermion.py b/crates/binding-python/cqlib/qis/fermion.py new file mode 100644 index 00000000..ffabc726 --- /dev/null +++ b/crates/binding-python/cqlib/qis/fermion.py @@ -0,0 +1,65 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Structured fermionic algebra and fermion-to-qubit mappings. + +Modes are numbered from zero. A product A * B applies B first. Jordan-Wigner +maps mode p to qubit p, with a Z chain on modes below p; qubit 0 is the least +significant bit. Core imposes no chemical or spin-orbital ordering. + +The excitation generator is G = i(T - T†), where targets supply creators in +input order and sources supply annihilators in reverse input order. Evolving +the mapped generator implements exp(-i theta G) = exp(theta (T - T†)). +""" + +from __future__ import annotations + +from typing import Protocol, Sequence, runtime_checkable + +from .._native import qis as _qis_module +from .hamiltonian import Hamiltonian + +FermionicLadder = _qis_module.fermion.FermionicLadder +FermionicOp = _qis_module.fermion.FermionicOp +JordanWignerMapper = _qis_module.fermion.JordanWignerMapper + + +@runtime_checkable +class FermionToQubitMapper(Protocol): + """Structural contract for operator mappings, including non-Hermitian inputs. + + Implementations need not inherit this protocol. Runtime checks establish + member presence only; callers must still honor signatures and semantics. + """ + + def map_operator(self, op: FermionicOp) -> Hamiltonian: ... + def num_qubits(self, num_modes: int) -> int: ... + + +@runtime_checkable +class OccupationStateMapper(Protocol): + """Separate contract for computational-basis occupation encodings. + + occupation[p] denotes mode p and returned bits[p] addresses qubit p. + Not every operator mapping has a computational-basis occupation encoding. + """ + + def map_occupation(self, occupation: Sequence[int]) -> list[bool]: ... + + +__all__ = [ + "FermionicLadder", + "FermionicOp", + "FermionToQubitMapper", + "OccupationStateMapper", + "JordanWignerMapper", +] diff --git a/crates/binding-python/cqlib/qis/fermion.pyi b/crates/binding-python/cqlib/qis/fermion.pyi new file mode 100644 index 00000000..422893eb --- /dev/null +++ b/crates/binding-python/cqlib/qis/fermion.pyi @@ -0,0 +1,149 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Typed interfaces for structured fermionic algebra and sparse mappings.""" + +from typing import ( + Iterable, + Literal, + Protocol, + Sequence, + TypeAlias, + final, + runtime_checkable, +) +from .hamiltonian import Hamiltonian + +_Coefficient: TypeAlias = complex | float | int + +@final +class FermionicLadder: + """Immutable ladder, constructed with create or annihilate, not directly.""" + @staticmethod + def create(mode: int) -> FermionicLadder: ... + @staticmethod + def annihilate(mode: int) -> FermionicLadder: ... + @property + def mode(self) -> int: ... + @property + def kind(self) -> Literal["create", "annihilate"]: ... + def adjoint(self) -> FermionicLadder: ... + def __eq__(self, other: object, /) -> bool: ... + def __hash__(self) -> int: ... + def __repr__(self) -> str: ... + +@final +class FermionicOp: + """Mutable complex sum of ordered products. B acts first in A * B. + + Identical ordered products merge exactly; no implicit normal ordering or + numerical truncation occurs. Mode counts are retained for zero and identity. + """ + + __hash__: None # type: ignore[assignment] + def __new__(cls, num_modes: int) -> FermionicOp: ... + @staticmethod + def identity(num_modes: int) -> FermionicOp: ... + @staticmethod + def from_term( + num_modes: int, + term: Iterable[FermionicLadder], + coefficient: _Coefficient = 1.0, + ) -> FermionicOp: ... + @staticmethod + def from_terms( + num_modes: int, + terms: Iterable[tuple[Iterable[FermionicLadder], _Coefficient]], + ) -> FermionicOp: ... + @staticmethod + def creation(num_modes: int, mode: int) -> FermionicOp: ... + @staticmethod + def annihilation(num_modes: int, mode: int) -> FermionicOp: ... + @staticmethod + def number(num_modes: int, mode: int) -> FermionicOp: ... + @staticmethod + def total_number(num_modes: int) -> FermionicOp: ... + @staticmethod + def excitation_generator( + num_modes: int, sources: Sequence[int], targets: Sequence[int] + ) -> FermionicOp: + """G = i(T - T†); targets in order, source annihilators in reverse order. + + Lists must be nonempty, equally sized, unique and disjoint. Input order + is preserved, with no implicit sorting or factorial normalization. + """ + ... + @property + def num_modes(self) -> int: ... + @property + def num_terms(self) -> int: ... + @property + def terms(self) -> list[tuple[tuple[FermionicLadder, ...], complex]]: + """Independent snapshot in deterministic structural order.""" + ... + def is_zero(self) -> bool: + """Whether the stored sum is empty; use equiv to test algebraic zero.""" + ... + def add_term( + self, term: Iterable[FermionicLadder], coefficient: _Coefficient = 1.0 + ) -> None: + """Modify in place; errors leave this object unchanged.""" + ... + def adjoint(self) -> FermionicOp: ... + def normal_order(self) -> FermionicOp: + """Return a new expansion: creators first, ascending modes in each group.""" + ... + def scaled(self, factor: _Coefficient) -> FermionicOp: ... + def chop(self, *, atol: float = 0.0) -> None: + """Remove terms with complex magnitude <= atol, in place.""" + ... + def equiv(self, other: FermionicOp, *, atol: float = 0.0) -> bool: ... + def is_hermitian(self, *, atol: float = 0.0) -> bool: ... + def __add__(self, other: FermionicOp, /) -> FermionicOp: ... + def __sub__(self, other: FermionicOp, /) -> FermionicOp: ... + def __mul__(self, other: FermionicOp | _Coefficient, /) -> FermionicOp: ... + def __rmul__(self, other: _Coefficient, /) -> FermionicOp: ... + def __neg__(self) -> FermionicOp: ... + def __eq__(self, other: object, /) -> bool: + """Structural equality; use equiv for algebraic equivalence.""" + ... + def copy(self) -> FermionicOp: ... + def __copy__(self) -> FermionicOp: ... + def __deepcopy__(self, memo: dict[int, object]) -> FermionicOp: ... + def __repr__(self) -> str: ... + def __str__(self) -> str: ... + +@runtime_checkable +class FermionToQubitMapper(Protocol): + def map_operator(self, op: FermionicOp) -> Hamiltonian: ... + def num_qubits(self, num_modes: int) -> int: ... + +@runtime_checkable +class OccupationStateMapper(Protocol): + def map_occupation(self, occupation: Sequence[int]) -> list[bool]: ... + +@final +class JordanWignerMapper: + """Mode p maps to qubit p; Z chain uses modes below p. Qubit 0 is LSB.""" + def __init__(self) -> None: ... + def map_operator(self, op: FermionicOp) -> Hamiltonian: ... + def num_qubits(self, num_modes: int) -> int: ... + def map_occupation(self, occupation: Sequence[int]) -> list[bool]: ... + def __repr__(self) -> str: ... + +__all__ = [ + "FermionicLadder", + "FermionicOp", + "FermionToQubitMapper", + "OccupationStateMapper", + "JordanWignerMapper", +] diff --git a/crates/binding-python/cqlib/qis/hamiltonian.py b/crates/binding-python/cqlib/qis/hamiltonian.py index c5f6b95f..20a1a58d 100644 --- a/crates/binding-python/cqlib/qis/hamiltonian.py +++ b/crates/binding-python/cqlib/qis/hamiltonian.py @@ -12,8 +12,12 @@ """Hamiltonian observable wrapper.""" +from typing import TypeAlias + from .._native import qis as _qis_module +Coefficient: TypeAlias = float | int | complex | tuple[float, float] + Hamiltonian = _qis_module.Hamiltonian __all__ = ["Hamiltonian"] diff --git a/crates/binding-python/cqlib/qis/hamiltonian.pyi b/crates/binding-python/cqlib/qis/hamiltonian.pyi index 3210e3a8..61d43dd6 100644 --- a/crates/binding-python/cqlib/qis/hamiltonian.pyi +++ b/crates/binding-python/cqlib/qis/hamiltonian.pyi @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -from typing import List, Tuple, Union, final, Sequence, Dict +from typing import List, Tuple, Union, final, Sequence, Dict, Iterable import numpy as np @@ -180,6 +180,52 @@ class Hamiltonian: """Returns ``True`` if all Pauli terms mutually commute.""" ... + @staticmethod + def from_terms( + num_qubits: int, + terms: Iterable[tuple[PauliString, complex | float | int]], + ) -> Hamiltonian: + """Validate, absorb phases and merge duplicates, removing exact zeros only.""" + ... + + def normalized(self) -> Hamiltonian: + """Return a validated, merged copy without numerical truncation.""" + ... + + def normalized_hermitian(self) -> Hamiltonian: + """Normalize and project imaginary residuals <= 1e-10; reject larger ones.""" + ... + + def add(self, other: Hamiltonian) -> Hamiltonian: + """Return a validated, merged sum; legacy + and += retain concatenation.""" + ... + + def scaled(self, factor: complex | float | int) -> Hamiltonian: ... + def adjoint(self) -> Hamiltonian: ... + def chop(self, *, atol: float = 0.0) -> None: + """Normalize and truncate by complex magnitude, in place and atomically.""" + ... + + def equiv(self, other: Hamiltonian, *, atol: float = 0.0) -> bool: ... + def is_hermitian(self, *, atol: float = 0.0) -> bool: + """Compare with adjoint; coefficient criterion is 2*abs(imag) <= atol.""" + ... + + def tensor(self, other: Hamiltonian) -> Hamiltonian: + """Return self tensor other, placing other on low qubits.""" + ... + + def remap_qubits(self, mapping: Sequence[int], target_width: int) -> Hamiltonian: + """Embed mapping[source] = destination, with identity on unused targets.""" + ... + + def __sub__(self, other: Hamiltonian, /) -> Hamiltonian: ... + def __mul__(self, other: Hamiltonian | complex | float | int, /) -> Hamiltonian: + """Operator product AB (B acts first), or scalar multiplication.""" + ... + + def __rmul__(self, other: complex | float | int, /) -> Hamiltonian: ... + def __neg__(self) -> Hamiltonian: ... def to_matrix(self) -> np.ndarray: """Computes the dense matrix representation as a NumPy array. @@ -206,6 +252,10 @@ class Hamiltonian: Returns: The real expectation value. + + Raises: + ValueError: If the observable is not Hermitian or input dimensions differ. + ValueError: If original or merged coefficients are non-finite. """ ... @@ -217,6 +267,10 @@ class Hamiltonian: Returns: The real expectation value. + + Raises: + ValueError: If the observable is not Hermitian or input dimensions differ. + ValueError: If original or merged coefficients are non-finite. """ ... @@ -231,10 +285,15 @@ class Hamiltonian: Returns: The real expectation value. + + Raises: + ValueError: If the observable is not Hermitian, input dimensions differ, + or no compatible measurement basis is available. + ValueError: If original or merged coefficients are non-finite. """ ... - def __add__(self, other: "Hamiltonian") -> "Hamiltonian": + def __add__(self, other: "Hamiltonian", /) -> "Hamiltonian": """Adds two Hamiltonians together. Note: This performs a simple lazy concatenation of the term lists. @@ -260,7 +319,7 @@ class Hamiltonian: """ ... - def __iadd__(self, other: "Hamiltonian") -> "Hamiltonian": + def __iadd__(self, other: "Hamiltonian", /) -> "Hamiltonian": """In-place addition of another Hamiltonian. Args: @@ -274,7 +333,7 @@ class Hamiltonian: """ ... - def __eq__(self, other: object) -> bool: + def __eq__(self, other: object, /) -> bool: """Checks if two Hamiltonians are equal.""" ... @@ -332,7 +391,8 @@ class Hamiltonian: """Computes the variance for a statevector. Raises: - ValueError: If the Hamiltonian is not Hermitian or qubit counts differ. + ValueError: If the Hamiltonian is not Hermitian, qubit counts differ, + or original or merged coefficients are non-finite. """ ... @@ -343,3 +403,13 @@ class Hamiltonian: A new Hamiltonian instance with the same terms. """ ... + + def __copy__(self) -> "Hamiltonian": + """Return an independent copy via copy.copy().""" + ... + + def __deepcopy__(self, memo: dict) -> "Hamiltonian": + """Return an independent copy via copy.deepcopy().""" + ... + +__all__ = ["Hamiltonian"] diff --git a/crates/binding-python/cqlib/qis/pauli.pyi b/crates/binding-python/cqlib/qis/pauli.pyi index c7f0ee15..dd14c3d8 100644 --- a/crates/binding-python/cqlib/qis/pauli.pyi +++ b/crates/binding-python/cqlib/qis/pauli.pyi @@ -289,7 +289,8 @@ class PauliString: The expectation value as a float. Raises: - ValueError: If state string length doesn't match num_qubits or contains invalid chars. + ValueError: If the Pauli string is not Hermitian, or a state string + has the wrong length or contains invalid characters. """ ... @@ -301,6 +302,9 @@ class PauliString: Returns: The real expectation value. + + Raises: + ValueError: If the observable is not Hermitian or input dimensions differ. """ ... @@ -312,6 +316,9 @@ class PauliString: Returns: The real expectation value. + + Raises: + ValueError: If the observable is not Hermitian or input dimensions differ. """ ... @@ -326,6 +333,10 @@ class PauliString: Returns: The real expectation value. + + Raises: + ValueError: If the observable is not Hermitian, input dimensions differ, + or no compatible measurement basis is available. """ ... diff --git a/crates/binding-python/cqlib/qis/state/density_matrix.pyi b/crates/binding-python/cqlib/qis/state/density_matrix.pyi index 61515eff..994e151b 100644 --- a/crates/binding-python/cqlib/qis/state/density_matrix.pyi +++ b/crates/binding-python/cqlib/qis/state/density_matrix.pyi @@ -59,6 +59,9 @@ class DensityMatrix: Returns: A new DensityMatrix instance in the ground state + Raises: + ValueError: If the dimension is unrepresentable or state allocation fails. + Examples: >>> dm = DensityMatrix(2) # |00⟩⟨00| state """ @@ -572,7 +575,8 @@ class DensityMatrix: The expectation value as a real number Raises: - ValueError: If the qubit counts don't match or the observable type is invalid + ValueError: If qubit counts differ, the observable type is invalid, + the observable is not Hermitian, or its coefficients are non-finite. """ ... diff --git a/crates/binding-python/cqlib/qis/state/density_matrix_noise.pyi b/crates/binding-python/cqlib/qis/state/density_matrix_noise.pyi index fc37fcd2..67706b5f 100644 --- a/crates/binding-python/cqlib/qis/state/density_matrix_noise.pyi +++ b/crates/binding-python/cqlib/qis/state/density_matrix_noise.pyi @@ -60,6 +60,9 @@ class DensityMatrixNoise: Returns: A new DensityMatrixNoise instance + Raises: + ValueError: If the dimension is unrepresentable or state allocation fails. + Examples: >>> from cqlib.qis.state import DensityMatrixNoise >>> # Simulator without noise (ideal simulation) @@ -118,10 +121,17 @@ class DensityMatrixNoise: """Computes measurement probabilities with readout error modeling. Args: - qubits: Indices of qubits to measure + qubits: Storage positions on which to apply readout errors. For a + circuit-bound state, noise is looked up using the circuit ID at + each position; unbound states use identity IDs. Returns: - A vector of probabilities for all 2^n computational basis states. + A vector of probabilities for all 2^num_qubits computational basis + states in storage order, independent of the selection order or size. + An empty selection applies no readout errors. + + Raises: + IndexError: A position is out of range, even without a noise model. """ ... @@ -304,7 +314,8 @@ class DensityMatrixNoise: The expectation value as a real number Raises: - ValueError: If the qubit counts don't match or the observable type is invalid + ValueError: If qubit counts differ, the observable type is invalid, + the observable is not Hermitian, or its coefficients are non-finite. """ ... diff --git a/crates/binding-python/cqlib/qis/state/statevector.pyi b/crates/binding-python/cqlib/qis/state/statevector.pyi index bd997414..6a8e080e 100644 --- a/crates/binding-python/cqlib/qis/state/statevector.pyi +++ b/crates/binding-python/cqlib/qis/state/statevector.pyi @@ -61,6 +61,9 @@ class Statevector: Returns: A new Statevector instance in the ground state + Raises: + ValueError: If the dimension is unrepresentable or state allocation fails. + Examples: >>> sv = Statevector(2) # |00⟩ state """ @@ -559,7 +562,8 @@ class Statevector: The expectation value as a real number Raises: - ValueError: If the qubit counts don't match or the observable type is invalid + ValueError: If qubit counts differ, the observable type is invalid, + the observable is not Hermitian, or its coefficients are non-finite. """ ... diff --git a/crates/binding-python/cqlib/visualization/__init__.py b/crates/binding-python/cqlib/visualization/__init__.py index aef02055..f7c2bdd0 100644 --- a/crates/binding-python/cqlib/visualization/__init__.py +++ b/crates/binding-python/cqlib/visualization/__init__.py @@ -196,7 +196,12 @@ def plot_state_paulivec( figsize=None, output_path=None, ): - """Render Pauli-basis expectation values as SVG.""" + """Render Pauli-basis expectation values as SVG. + + Labels follow PauliString by default: the rightmost character acts on + qubit 0, so IX measures X on qubit 0 of a two-qubit state. Setting + reverse_bits=True reverses each label without changing its coefficient. + """ svg = _visualization_module.plot_state_paulivec( state, title=title, diff --git a/crates/binding-python/pyproject.toml b/crates/binding-python/pyproject.toml index 1d92fce9..837ae1be 100644 --- a/crates/binding-python/pyproject.toml +++ b/crates/binding-python/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "cqlib" description = "A high-performance quantum computing SDK with a Rust core and Python bindings." -requires-python = ">=3.10" +requires-python = ">=3.11" license = "Apache-2.0" readme = "README.md" authors = [ @@ -15,11 +15,11 @@ classifiers = [ "Programming Language :: Rust", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", + "Programming Language :: Python :: 3.15", "Topic :: Software Development :: Libraries", "Typing :: Typed", ] diff --git a/crates/binding-python/src/circuit/ansatz/hamiltonian_evolution.rs b/crates/binding-python/src/circuit/ansatz/hamiltonian_evolution.rs index ab7e3c6b..dc439f35 100644 --- a/crates/binding-python/src/circuit/ansatz/hamiltonian_evolution.rs +++ b/crates/binding-python/src/circuit/ansatz/hamiltonian_evolution.rs @@ -361,8 +361,9 @@ impl From for PauliEvolutionAnsatz { impl PyPauliEvolutionAnsatz { /// Creates a new ``PauliEvolutionAnsatz`` from a Hamiltonian. /// - /// The Hamiltonian is automatically **simplified** (phases absorbed, duplicate - /// terms merged, near-zero terms removed) before any further processing. + /// The Hamiltonian is normalized (phases absorbed and duplicate terms merged). + /// Imaginary residuals with magnitude <= 1e-10 are projected to zero; larger + /// ones are rejected. Every nonzero real coefficient is retained. /// /// Default strategy is :meth:`EvolutionStrategy.auto` with ``steps=1``. /// diff --git a/crates/binding-python/src/circuit/circuit_impl.rs b/crates/binding-python/src/circuit/circuit_impl.rs index 678fa991..5e2f0f10 100644 --- a/crates/binding-python/src/circuit/circuit_impl.rs +++ b/crates/binding-python/src/circuit/circuit_impl.rs @@ -1007,7 +1007,9 @@ impl PyCircuit { .map_err(|error| PyCircuitError::new_err(error.to_string())) } - /// Appends another circuit, optionally remapping its qubits. + /// Appends another circuit, optionally remapping its qubits in source insertion order. + /// Explicit targets must be distinct and already present in this circuit. + /// Errors leave this circuit unchanged; existing classical handles remain valid. #[pyo3(signature = (other, qubits=None))] fn compose(&mut self, other: &PyCircuit, qubits: Option) -> PyResult<()> { let qubits = qubits.map(Vec::from); diff --git a/crates/binding-python/src/circuit/classical_data.rs b/crates/binding-python/src/circuit/classical_data.rs new file mode 100644 index 00000000..c16d7350 --- /dev/null +++ b/crates/binding-python/src/circuit/classical_data.rs @@ -0,0 +1,85 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Python wrapper for runtime classical data operations. + +use crate::circuit::{PyClassicalExpr, PyClassicalValue, PyClassicalVar}; +use cqlib_core::circuit::gate::ClassicalDataOp; +use pyo3::prelude::*; + +/// Runtime classical data operation: a store into a mutable classical +/// variable, or a measurement producing an immutable classical value. +/// +/// Instances are obtained from `Instruction.classical_data` / +/// `ValueInstruction.classical_data`; they are not constructed directly. +#[pyclass(name = "ClassicalDataOp", module = "cqlib.circuit", from_py_object)] +#[derive(Debug, Clone)] +pub struct PyClassicalDataOp { + pub(crate) inner: ClassicalDataOp, +} + +impl From for PyClassicalDataOp { + fn from(inner: ClassicalDataOp) -> Self { + Self { inner } + } +} + +#[pymethods] +impl PyClassicalDataOp { + /// Returns the operation kind: `'store'`, `'measure_bit'`, or + /// `'measure_bits'`. + #[getter] + pub fn kind(&self) -> &'static str { + self.inner.name() + } + + /// Returns the store target variable if this is a store operation, + /// None otherwise. + #[getter] + pub fn target(&self) -> Option { + self.inner.target().map(PyClassicalVar::from) + } + + /// Returns the stored expression if this is a store operation, + /// None otherwise. + #[getter] + pub fn value(&self) -> Option { + self.inner.value().cloned().map(PyClassicalExpr::from) + } + + /// Returns the immutable value receiving the result if this is a + /// measurement operation, None otherwise. + #[getter] + pub fn result(&self) -> Option { + self.inner.result().map(PyClassicalValue::from) + } + + fn __repr__(&self) -> String { + format!("ClassicalDataOp({})", self.inner.name()) + } + + fn __eq__(&self, other: &Bound<'_, PyAny>) -> PyResult { + if !other.is_instance_of::() { + return Ok(false); + } + let other = other.extract::()?; + Ok(self.inner == other.inner) + } + + fn __copy__(&self) -> Self { + self.clone() + } + + fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> Self { + self.clone() + } +} diff --git a/crates/binding-python/src/circuit/instruction.rs b/crates/binding-python/src/circuit/instruction.rs index 6aeed35a..08cbeb17 100644 --- a/crates/binding-python/src/circuit/instruction.rs +++ b/crates/binding-python/src/circuit/instruction.rs @@ -19,7 +19,8 @@ use crate::circuit::error::CircuitError as PyCircuitError; use crate::circuit::gate::standard::standard_gate_from_name; use crate::circuit::{ - PyCircuitGate, PyClassicalControlOp, PyDirective, PyMcGate, PyStandardGate, PyUnitaryGate, + PyCircuitGate, PyClassicalControlOp, PyClassicalDataOp, PyDirective, PyMcGate, PyStandardGate, + PyUnitaryGate, }; use crate::utils::python_string_literal; use cqlib_core::circuit::{Instruction, ValueInstruction}; @@ -180,10 +181,50 @@ impl PyInstruction { #[getter] fn directive(&self) -> Option { - match &self.inner { - Instruction::Directive(directive) => Some(PyDirective::from(*directive)), - _ => None, - } + self.inner.directive().map(PyDirective::from) + } + + /// Returns the multi-controlled gate if this is an mc-gate instruction, + /// None otherwise. + /// + /// The returned gate carries no bound parameters: parameters belong to the + /// operation (`Operation.params` / `ValueOperation.params`), not to the + /// instruction. + #[getter] + fn mc_gate(&self) -> Option { + self.inner.mc_gate().cloned().map(|gate| PyMcGate { + inner: gate, + params: vec![], + }) + } + + /// Returns the unitary gate if this is a unitary instruction, None otherwise. + /// + /// Parameters of a parametric unitary belong to the operation + /// (`Operation.params` / `ValueOperation.params`), not to the instruction. + #[getter] + fn unitary_gate(&self) -> Option { + self.inner.unitary_gate().cloned().map(PyUnitaryGate::from) + } + + /// Returns the circuit-backed gate if this is a circuit-gate instruction, + /// None otherwise. + /// + /// Parameters belong to the operation (`Operation.params` / + /// `ValueOperation.params`), not to the instruction. + #[getter] + fn circuit_gate(&self) -> Option { + self.inner.circuit_gate().cloned().map(PyCircuitGate::from) + } + + /// Returns the classical data operation if this is a classical-data + /// instruction, None otherwise. + #[getter] + fn classical_data(&self) -> Option { + self.inner + .classical_data() + .cloned() + .map(PyClassicalDataOp::from) } fn __str__(&self) -> String { @@ -327,6 +368,48 @@ impl PyValueInstruction { self.inner.directive().map(PyDirective::from) } + /// Returns the multi-controlled gate if this is an mc-gate instruction, + /// None otherwise. + /// + /// The returned gate carries no bound parameters: parameters belong to the + /// operation (`ValueOperation.params`), not to the instruction. + #[getter] + fn mc_gate(&self) -> Option { + self.inner.mc_gate().cloned().map(|gate| PyMcGate { + inner: gate, + params: vec![], + }) + } + + /// Returns the unitary gate if this is a unitary instruction, None otherwise. + /// + /// Parameters of a parametric unitary belong to the operation + /// (`ValueOperation.params`), not to the instruction. + #[getter] + fn unitary_gate(&self) -> Option { + self.inner.unitary_gate().cloned().map(PyUnitaryGate::from) + } + + /// Returns the circuit-backed gate if this is a circuit-gate instruction, + /// None otherwise. + /// + /// Parameters belong to the operation (`ValueOperation.params`), not to + /// the instruction. + #[getter] + fn circuit_gate(&self) -> Option { + self.inner.circuit_gate().cloned().map(PyCircuitGate::from) + } + + /// Returns the classical data operation if this is a classical-data + /// instruction, None otherwise. + #[getter] + fn classical_data(&self) -> Option { + self.inner + .classical_data() + .cloned() + .map(PyClassicalDataOp::from) + } + #[getter] fn instruction(&self) -> Option { self.inner @@ -337,10 +420,10 @@ impl PyValueInstruction { #[getter] fn classical_control(&self) -> Option { - match &self.inner { - ValueInstruction::ClassicalControl(control) => Some(control.clone().into()), - ValueInstruction::Instruction(_) => None, - } + self.inner + .classical_control() + .cloned() + .map(PyClassicalControlOp::from) } fn __str__(&self) -> String { @@ -371,11 +454,96 @@ impl PyValueInstruction { #[cfg(test)] mod tests { use super::*; - use cqlib_core::circuit::{Parameter, StandardGate}; + use cqlib_core::circuit::gate::{ + CircuitGate, ClassicalDataOp, FrozenCircuit, MCGate, UnitaryGate, + }; + use cqlib_core::circuit::{ + Circuit, CircuitId, ClassicalType, ClassicalValue, Parameter, StandardGate, + }; #[test] fn storage_instruction_rejects_bound_gate_parameters() { let gate = PyStandardGate::from(StandardGate::RX, vec![Parameter::symbol("theta")]); assert!(PyInstruction::from_standard_gate(gate).is_err()); } + + #[test] + fn storage_instruction_payload_accessors_return_cloned_gates() { + let mc = PyInstruction::from(Instruction::McGate(Box::new(MCGate::new( + 2, + StandardGate::X, + )))); + let mc_gate = mc.mc_gate().expect("mc gate"); + assert_eq!(mc_gate.inner.num_ctrl_qubits(), 2); + assert_eq!(*mc_gate.inner.base_gate(), StandardGate::X); + assert!(mc_gate.params.is_empty()); + assert!(mc.unitary_gate().is_none()); + assert!(mc.circuit_gate().is_none()); + assert!(mc.classical_data().is_none()); + + let unitary = PyInstruction::from(Instruction::UnitaryGate(Box::new(UnitaryGate::new( + "oracle", 2, 1, + )))); + let unitary_gate = unitary.unitary_gate().expect("unitary gate"); + assert_eq!(unitary_gate.label(), "oracle"); + assert_eq!(unitary_gate.num_qubits(), 2); + assert!(unitary.mc_gate().is_none()); + + let circuit_gate = + CircuitGate::new("composite", FrozenCircuit::new(Circuit::new(1))).unwrap(); + let circuit = PyInstruction::from(Instruction::CircuitGate(Box::new(circuit_gate))); + assert!(circuit.circuit_gate().is_some()); + assert!(circuit.mc_gate().is_none()); + + let standard = PyInstruction::from(Instruction::Standard(StandardGate::H)); + assert!(standard.mc_gate().is_none()); + assert!(standard.unitary_gate().is_none()); + assert!(standard.circuit_gate().is_none()); + assert!(standard.classical_data().is_none()); + } + + #[test] + fn storage_instruction_classical_data_accessor_returns_operation() { + let result = ClassicalValue::new(CircuitId::new(), 0, ClassicalType::Bit); + let instruction = + PyInstruction::from(Instruction::ClassicalData(ClassicalDataOp::MeasureBit { + result, + })); + + let data = instruction.classical_data().expect("classical data"); + assert_eq!(data.kind(), "measure_bit"); + assert_eq!(data.result().map(|value| value.inner), Some(result)); + assert!(data.target().is_none()); + assert!(data.value().is_none()); + } + + #[test] + fn value_instruction_payload_accessors_delegate() { + let mc = PyValueInstruction::from(ValueInstruction::from_instruction(Instruction::McGate( + Box::new(MCGate::new(3, StandardGate::Z)), + ))); + let mc_gate = mc.mc_gate().expect("mc gate"); + assert_eq!(mc_gate.inner.num_ctrl_qubits(), 3); + assert!(mc_gate.params.is_empty()); + assert!(mc.unitary_gate().is_none()); + assert!(mc.circuit_gate().is_none()); + assert!(mc.classical_data().is_none()); + + let unitary = PyValueInstruction::from(ValueInstruction::from_instruction( + Instruction::UnitaryGate(Box::new(UnitaryGate::new("oracle", 1, 0))), + )); + assert_eq!( + unitary.unitary_gate().map(|gate| gate.label()), + Some("oracle".to_string()) + ); + + let control = + PyValueInstruction::from_classical_control(crate::circuit::PyClassicalControlOp { + inner: cqlib_core::circuit::ValueClassicalControlOp::Break, + }); + assert!(control.mc_gate().is_none()); + assert!(control.unitary_gate().is_none()); + assert!(control.circuit_gate().is_none()); + assert!(control.classical_data().is_none()); + } } diff --git a/crates/binding-python/src/circuit/mod.rs b/crates/binding-python/src/circuit/mod.rs index ab68fa4c..6ddc3555 100644 --- a/crates/binding-python/src/circuit/mod.rs +++ b/crates/binding-python/src/circuit/mod.rs @@ -21,6 +21,7 @@ pub mod bit; pub mod circuit_impl; pub mod circuit_to_matrix; pub mod classical; +pub mod classical_data; pub mod classical_expr; pub mod control_flow; pub mod dag; @@ -42,6 +43,7 @@ pub use circuit_to_matrix::py_circuit_to_matrix; pub use classical::{ PyCircuitId, PyClassicalType, PyClassicalValue, PyClassicalVar, PyMeasurement, }; +pub use classical_data::PyClassicalDataOp; pub use classical_expr::PyClassicalExpr; pub use control_flow::{ PyClassicalControlOp, PySwitchBuilder, PyValueControlBody, PyValueSwitchCase, @@ -73,6 +75,7 @@ pub(crate) fn register_circuit_module(parent: &Bound<'_, PyModule>) -> PyResult< m.add_class::()?; m.add_class::()?; m.add_class::()?; + m.add_class::()?; m.add_class::()?; m.add_class::()?; m.add_class::()?; diff --git a/crates/binding-python/src/circuit/parameter.rs b/crates/binding-python/src/circuit/parameter.rs index dae61327..7f11c551 100644 --- a/crates/binding-python/src/circuit/parameter.rs +++ b/crates/binding-python/src/circuit/parameter.rs @@ -228,7 +228,8 @@ impl PyParameter { self.inner.as_symbol() } - /// Substitutes multiple symbols and simplifies the resulting expression. + /// Simultaneously substitutes symbols and simplifies the resulting expression. + /// Inserted expressions are not substituted again; the original is unchanged. fn substitute(&self, bindings: HashMap) -> Self { let bindings = bindings .into_iter() diff --git a/crates/binding-python/src/compile/transform/decompose/block_zxz.rs b/crates/binding-python/src/compile/transform/decompose/block_zxz.rs new file mode 100644 index 00000000..d6fe47b0 --- /dev/null +++ b/crates/binding-python/src/compile/transform/decompose/block_zxz.rs @@ -0,0 +1,129 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +use super::unitary::extract_complex_matrix; +use crate::circuit::PyCircuit; +use crate::compile::error::compiler_error_to_py_err; +use crate::utils::hash_value; +use cqlib_core::compile::transform::decompose::{ + BlockZxzDecomposeOptions, decompose_block_zxz_with_options, +}; +use pyo3::prelude::*; + +/// CX reductions for recursive Block-ZXZ synthesis. +#[pyclass( + name = "BlockZxzDecomposeOptions", + module = "cqlib.compile.transform.decompose.block_zxz", + frozen, + from_py_object +)] +#[derive(Clone, Copy, Debug)] +pub(super) struct Options(pub(super) BlockZxzDecomposeOptions); + +#[pymethods] +impl Options { + #[new] + #[pyo3(signature = (*, opt_a1=true, opt_a2=true, opt_a2_force=false))] + fn new(opt_a1: bool, opt_a2: bool, opt_a2_force: bool) -> Self { + Self(BlockZxzDecomposeOptions { + opt_a1, + opt_a2, + opt_a2_force, + }) + } + /// Absorb the outer UCRZ boundary CX gates (Section 5.2). + #[getter] + fn opt_a1(&self) -> bool { + self.0.opt_a1 + } + /// Transfer diagonal remainders between two-qubit leaves (Section 5.1). + #[getter] + fn opt_a2(&self) -> bool { + self.0.opt_a2 + } + /// Permit an enabled A.2 reduction on block-diagonal inputs. + #[getter] + fn opt_a2_force(&self) -> bool { + self.0.opt_a2_force + } + /// Return options for unoptimized synthesis. + #[staticmethod] + fn none() -> Self { + Self::new(false, false, false) + } + + fn __repr__(&self) -> String { + self.repr_value() + } + + fn __eq__(&self, other: &Self) -> bool { + self.0 == other.0 + } + + fn __hash__(&self) -> u64 { + hash_value(&self.0) + } + + fn __copy__(&self) -> Self { + *self + } + + fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> Self { + *self + } +} + +impl Options { + pub(super) fn repr_value(&self) -> String { + let py_bool = |value: bool| if value { "True" } else { "False" }; + format!( + "BlockZxzDecomposeOptions(opt_a1={}, opt_a2={}, opt_a2_force={})", + py_bool(self.0.opt_a1), + py_bool(self.0.opt_a2), + py_bool(self.0.opt_a2_force), + ) + } +} + +/// Return a standard-gate circuit for a finite unitary, including its scalar phase. +#[pyfunction(name = "decompose_block_zxz", signature = (matrix, atol=1e-10))] +fn decompose(py: Python<'_>, matrix: Bound<'_, PyAny>, atol: f64) -> PyResult { + with_options(py, matrix, atol, None) +} + +/// Set the A.1/A.2 reductions. A.2 is disabled on block diagonals unless forced. +#[pyfunction(name = "decompose_block_zxz_with_options", signature = (matrix, atol=1e-10, *, options=None))] +fn with_options( + py: Python<'_>, + matrix: Bound<'_, PyAny>, + atol: f64, + options: Option, +) -> PyResult { + let matrix = extract_complex_matrix(py, matrix)?; + let options = options.map(|o| o.0).unwrap_or_default(); + py.detach(move || decompose_block_zxz_with_options(&matrix, atol, &options)) + .map(Into::into) + .map_err(compiler_error_to_py_err) +} + +pub(super) fn register(parent: &Bound<'_, PyModule>) -> PyResult<()> { + let m = PyModule::new(parent.py(), "block_zxz")?; + m.add_class::()?; + m.add_function(wrap_pyfunction!(decompose, &m)?)?; + m.add_function(wrap_pyfunction!(with_options, &m)?)?; + parent.add_submodule(&m)?; + parent + .py() + .import("sys")? + .getattr("modules")? + .set_item("cqlib._native.compile.transform.decompose.block_zxz", &m) +} diff --git a/crates/binding-python/src/compile/transform/decompose/config.rs b/crates/binding-python/src/compile/transform/decompose/config.rs index 16d212ad..458aec55 100644 --- a/crates/binding-python/src/compile/transform/decompose/config.rs +++ b/crates/binding-python/src/compile/transform/decompose/config.rs @@ -10,6 +10,7 @@ // copyright notice, and modified files need to carry a notice indicating // that they have been altered from the originals. +use super::block_zxz::Options as PyBlockZxzDecomposeOptions; use crate::circuit::PyInstruction; use crate::compile::error::compiler_error_to_py_err; use crate::compile::resource::{PyResourceLimits, PyResourcePolicy}; @@ -20,7 +21,9 @@ use cqlib_core::compile::CompilerError; use cqlib_core::compile::transform::decompose::unitary::{ TwoQubitSynthesisTarget, TwoQubitUnitaryDecomposeBasis, }; -use cqlib_core::compile::transform::decompose::{McGateDecomposeConfig, UnitaryDecomposeConfig}; +use cqlib_core::compile::transform::decompose::{ + BlockZxzDecomposeOptions, McGateDecomposeConfig, UnitaryDecomposeConfig, +}; use pyo3::prelude::*; /// Output interaction basis used for numeric two-qubit unitary synthesis. @@ -123,12 +126,13 @@ pub struct PyUnitaryDecomposeConfig { #[pymethods] impl PyUnitaryDecomposeConfig { #[new] - #[pyo3(signature = (*, two_qubit_basis=None, target_basis=None, recurse_control_flow=true))] + #[pyo3(signature = (*, two_qubit_basis=None, target_basis=None, recurse_control_flow=true, block_zxz_options=None))] fn new( py: Python<'_>, two_qubit_basis: Option, target_basis: Option>, recurse_control_flow: bool, + block_zxz_options: Option, ) -> PyResult { if two_qubit_basis.is_some() && target_basis.is_some() { return Err(compiler_error_to_py_err(CompilerError::InvalidInput( @@ -157,10 +161,12 @@ impl PyUnitaryDecomposeConfig { target_for_basis(basis.inner) }), }; + let block_zxz_options = block_zxz_options.map_or_else(Default::default, |value| value.0); Ok(Self { inner: UnitaryDecomposeConfig { two_qubit_target, recurse_control_flow, + block_zxz_options, }, two_qubit_basis, target_basis, @@ -184,22 +190,32 @@ impl PyUnitaryDecomposeConfig { self.inner.recurse_control_flow } + #[getter] + fn block_zxz_options(&self) -> PyBlockZxzDecomposeOptions { + PyBlockZxzDecomposeOptions(self.inner.block_zxz_options) + } + fn __repr__(&self) -> String { let two_qubit_basis = self.two_qubit_basis.map_or_else( || "None".to_string(), |basis| basis.repr_value().to_string(), ); let target_basis = format_target_basis_repr(&self.target_basis); - format!( - "UnitaryDecomposeConfig(two_qubit_basis={}, target_basis={}, recurse_control_flow={})", - two_qubit_basis, - target_basis, - if self.inner.recurse_control_flow { - "True" - } else { - "False" - } - ) + let recurse = if self.inner.recurse_control_flow { + "True" + } else { + "False" + }; + if self.inner.block_zxz_options == BlockZxzDecomposeOptions::default() { + format!( + "UnitaryDecomposeConfig(two_qubit_basis={two_qubit_basis}, target_basis={target_basis}, recurse_control_flow={recurse})", + ) + } else { + let block_zxz = PyBlockZxzDecomposeOptions(self.inner.block_zxz_options).repr_value(); + format!( + "UnitaryDecomposeConfig(two_qubit_basis={two_qubit_basis}, target_basis={target_basis}, recurse_control_flow={recurse}, block_zxz_options={block_zxz})", + ) + } } fn __eq__(&self, other: &Self) -> bool { diff --git a/crates/binding-python/src/compile/transform/decompose/mod.rs b/crates/binding-python/src/compile/transform/decompose/mod.rs index 07405723..70fec556 100644 --- a/crates/binding-python/src/compile/transform/decompose/mod.rs +++ b/crates/binding-python/src/compile/transform/decompose/mod.rs @@ -10,6 +10,7 @@ // copyright notice, and modified files need to carry a notice indicating // that they have been altered from the originals. +mod block_zxz; pub(crate) mod config; mod mc_gate; mod pass; @@ -47,6 +48,7 @@ pub(crate) fn register_decompose_module(parent: &Bound<'_, PyModule>) -> PyResul &m )?)?; + block_zxz::register(&m)?; unitary::register_unitary_module(&m)?; mc_gate::register_mc_gate_module(&m)?; diff --git a/crates/binding-python/src/compile/transform/decompose/pass.rs b/crates/binding-python/src/compile/transform/decompose/pass.rs index 648c6c91..ea7b1d3f 100644 --- a/crates/binding-python/src/compile/transform/decompose/pass.rs +++ b/crates/binding-python/src/compile/transform/decompose/pass.rs @@ -40,7 +40,7 @@ pub fn py_expand_definitions( .map_err(compiler_error_to_py_err) } -/// Synthesizes matrix-backed one- and two-qubit unitary gates. +/// Synthesizes matrix-backed numeric unitary gates. #[pyfunction(name = "decompose_unitaries")] #[pyo3(signature = (circuit, config=None))] pub fn py_decompose_unitaries( diff --git a/crates/binding-python/src/compile/transform/decompose/unitary.rs b/crates/binding-python/src/compile/transform/decompose/unitary.rs index 419ccaef..e4d56411 100644 --- a/crates/binding-python/src/compile/transform/decompose/unitary.rs +++ b/crates/binding-python/src/compile/transform/decompose/unitary.rs @@ -233,9 +233,15 @@ pub fn py_kak_decompose(py: Python<'_>, matrix: Bound<'_, PyAny>) -> PyResult, matrix: Bound<'_, PyAny>) -> PyResult> { +pub(super) fn extract_complex_matrix( + py: Python<'_>, + matrix: Bound<'_, PyAny>, +) -> PyResult> { let numpy = py.import("numpy")?; - let array = numpy.call_method1("array", (matrix, "complex128"))?; + // Require both C-contiguous layout and alignment so non-element-multiple + // byte strides (e.g. 40-byte row stride for 16-byte Complex64) and + // unaligned C-contiguous buffers are normalized before ndarray reads them. + let array = numpy.call_method1("require", (matrix, "complex128", ["C", "A"]))?; let array = array.cast_into::>().map_err(|_| { PyTypeError::new_err("matrix must be convertible to a two-dimensional complex128 array") })?; diff --git a/crates/binding-python/src/qis/entropy.rs b/crates/binding-python/src/qis/entropy.rs index 7f7ff362..756f9599 100644 --- a/crates/binding-python/src/qis/entropy.rs +++ b/crates/binding-python/src/qis/entropy.rs @@ -43,13 +43,20 @@ pub fn linear_entropy(dm: &PyDensityMatrix) -> PyResult { /// /// Args: /// dm (DensityMatrix): The density matrix representing the quantum state. -/// alpha (float): The order parameter. Must be positive. +/// alpha (float): Positive order, including 1 (Von Neumann entropy) +/// and positive infinity (min-entropy). /// /// Returns: /// float: The Rényi entropy in bits (base-2 logarithm). /// /// Raises: -/// ValueError: If alpha <= 0 or if eigendecomposition fails. +/// ValueError: If alpha is NaN or <= 0, eigendecomposition fails, +/// or no positive spectrum remains. +/// +/// Notes: +/// Non-diagonal spectra discard eigenvalues at or below +/// dimension * machine epsilon * largest eigenvalue as numerical zeros. +/// Diagonal spectra retain all positive entries. #[pyfunction] pub fn renyi_entropy(dm: &PyDensityMatrix, alpha: f64) -> PyResult { core_entropy::renyi_entropy(&dm.inner, alpha).map_err(qis_error_to_py_err) diff --git a/crates/binding-python/src/qis/fermion.rs b/crates/binding-python/src/qis/fermion.rs new file mode 100644 index 00000000..83a519cd --- /dev/null +++ b/crates/binding-python/src/qis/fermion.rs @@ -0,0 +1,506 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Structured fermionic operators and sparse mappings; algebra stays in Core. + +use super::hamiltonian::PyHamiltonian; +use super::qis_error_to_py_err; +use cqlib_core::qis::{ + FermionToQubitMapper, FermionicLadder, FermionicOp, JordanWignerMapper, OccupationStateMapper, +}; +use num_complex::Complex64; +use pyo3::basic::CompareOp; +use pyo3::exceptions::{PyIndexError, PyValueError}; +use pyo3::prelude::*; +use pyo3::types::{PyComplex, PyList, PyTuple}; +use std::collections::hash_map::DefaultHasher; +use std::hash::{Hash, Hasher}; + +// Respect Python's integer protocol, including type-level method lookup and +// validation of __index__ return values, rather than invoking the method directly. +fn integer_index<'py>(value: &Bound<'py, PyAny>) -> PyResult> { + // SAFETY: value is a live Python object under the GIL. PyNumber_Index returns + // a new owned reference, or NULL with an exception; Bound handles both cases. + unsafe { Bound::from_owned_ptr_or_err(value.py(), pyo3::ffi::PyNumber_Index(value.as_ptr())) } +} + +pub(super) fn index(value: &Bound<'_, PyAny>, is_count: bool) -> PyResult { + let integer = integer_index(value)?; + if integer.rich_compare(0, CompareOp::Lt)?.is_truthy()? { + return Err(if is_count { + PyValueError::new_err("register size must be nonnegative") + } else { + PyIndexError::new_err("mode indices must be nonnegative") + }); + } + integer.extract() +} + +fn indices(values: &Bound<'_, PyAny>) -> PyResult> { + values.try_iter()?.map(|v| index(&v?, false)).collect() +} + +fn ladders(term: &Bound<'_, PyAny>) -> PyResult> { + term.try_iter()? + .map(|v| Ok(v?.extract::>()?.inner)) + .collect() +} + +/// An immutable creation or annihilation operator on a zero-based mode. +#[pyclass( + name = "FermionicLadder", + module = "cqlib.qis.fermion", + frozen, + skip_from_py_object +)] +#[derive(Clone)] +pub struct PyFermionicLadder { + inner: FermionicLadder, +} + +#[pymethods] +impl PyFermionicLadder { + #[staticmethod] + /// Create an immutable creation ladder on a zero-based mode. + fn create(mode: &Bound<'_, PyAny>) -> PyResult { + Ok(Self { + inner: FermionicLadder::Create(index(mode, false)?), + }) + } + + #[staticmethod] + /// Create an immutable annihilation ladder on a zero-based mode. + fn annihilate(mode: &Bound<'_, PyAny>) -> PyResult { + Ok(Self { + inner: FermionicLadder::Annihilate(index(mode, false)?), + }) + } + + #[getter] + /// Zero-based mode index; the containing operator validates its range. + fn mode(&self) -> usize { + self.inner.mode() + } + + #[getter] + /// Ladder kind, either "create" or "annihilate". + fn kind(&self) -> &'static str { + match self.inner { + FermionicLadder::Create(_) => "create", + FermionicLadder::Annihilate(_) => "annihilate", + } + } + + /// Return a ladder on the same mode with creation and annihilation exchanged. + fn adjoint(&self) -> Self { + Self { + inner: self.inner.adjoint(), + } + } + + fn __eq__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + let py = other.py(); + match other.extract::>() { + Ok(rhs) => Ok((self.inner == rhs.inner) + .into_pyobject(py)? + .to_owned() + .into_any() + .unbind()), + Err(_) => Ok(py.NotImplemented()), + } + } + + fn __hash__(&self) -> isize { + let mut hasher = DefaultHasher::new(); + self.inner.hash(&mut hasher); + let hash = hasher.finish() as isize; + if hash == -1 { -2 } else { hash } + } + + fn __repr__(&self) -> String { + format!("FermionicLadder.{}({})", self.kind(), self.mode()) + } +} + +/// A finite complex sum of ordered fermionic products on a declared mode space. +/// +/// In A * B, B acts first. Products are not automatically normal ordered. +/// Only exact zero coefficients are removed; use chop for explicit truncation. +#[pyclass( + name = "FermionicOp", + module = "cqlib.qis.fermion", + skip_from_py_object +)] +#[derive(Clone)] +pub struct PyFermionicOp { + inner: FermionicOp, +} + +impl From for PyFermionicOp { + fn from(inner: FermionicOp) -> Self { + Self { inner } + } +} + +#[pymethods] +impl PyFermionicOp { + /// Construct the zero operator; num_modes is retained even for zero modes. + #[new] + fn new(num_modes: &Bound<'_, PyAny>) -> PyResult { + Ok(FermionicOp::new(index(num_modes, true)?).into()) + } + + #[staticmethod] + /// Return the identity on the declared mode space, including zero modes. + fn identity(num_modes: &Bound<'_, PyAny>) -> PyResult { + Ok(FermionicOp::identity(index(num_modes, true)?).into()) + } + + /// An empty product is identity, whereas an empty sum is zero. + #[staticmethod] + #[pyo3(signature = (num_modes, term, coefficient=Complex64::new(1.0, 0.0)), text_signature = "(num_modes, term, coefficient=1.0)")] + fn from_term( + num_modes: &Bound<'_, PyAny>, + term: &Bound<'_, PyAny>, + coefficient: Complex64, + ) -> PyResult { + FermionicOp::from_term(index(num_modes, true)?, ladders(term)?, coefficient) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Accept an iterable of (ordered ladders, coefficient) pairs and merge duplicates. + #[staticmethod] + fn from_terms(num_modes: &Bound<'_, PyAny>, terms: &Bound<'_, PyAny>) -> PyResult { + let mut result = FermionicOp::new(index(num_modes, true)?); + for item in terms.try_iter()? { + let item = item?; + let pair = item.cast::()?; + if pair.len() != 2 { + return Err(PyValueError::new_err( + "each term must be a pair (ladders, coefficient)", + )); + } + result + .add_term(ladders(&pair.get_item(0)?)?, pair.get_item(1)?.extract()?) + .map_err(qis_error_to_py_err)?; + } + Ok(result.into()) + } + + #[staticmethod] + /// Return a creation operator; invalid mode indices raise IndexError. + fn creation(num_modes: &Bound<'_, PyAny>, mode: &Bound<'_, PyAny>) -> PyResult { + FermionicOp::creation(index(num_modes, true)?, index(mode, false)?) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + #[staticmethod] + /// Return an annihilation operator; invalid mode indices raise IndexError. + fn annihilation(num_modes: &Bound<'_, PyAny>, mode: &Bound<'_, PyAny>) -> PyResult { + FermionicOp::annihilation(index(num_modes, true)?, index(mode, false)?) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + #[staticmethod] + /// Return the mode number operator a†_p a_p. + fn number(num_modes: &Bound<'_, PyAny>, mode: &Bound<'_, PyAny>) -> PyResult { + FermionicOp::number(index(num_modes, true)?, index(mode, false)?) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + #[staticmethod] + /// Return total particle number; zero modes yield the zero operator. + fn total_number(num_modes: &Bound<'_, PyAny>) -> PyResult { + Ok(FermionicOp::total_number(index(num_modes, true)?).into()) + } + + /// G = i(T - T†), with target creators followed by reversed source annihilators. + /// Input order is preserved; no spin-orbital ordering or factorial is imposed. + #[staticmethod] + fn excitation_generator( + num_modes: &Bound<'_, PyAny>, + sources: &Bound<'_, PyAny>, + targets: &Bound<'_, PyAny>, + ) -> PyResult { + FermionicOp::excitation_generator( + index(num_modes, true)?, + &indices(sources)?, + &indices(targets)?, + ) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + #[getter] + /// Declared number of modes, retained even for zero and identity operators. + fn num_modes(&self) -> usize { + self.inner.num_modes() + } + + #[getter] + /// Number of stored ordered products, before algebraic normal ordering. + fn num_terms(&self) -> usize { + self.inner.num_terms() + } + + /// Return an independent snapshot in deterministic structural order. + #[getter] + fn terms<'py>(&self, py: Python<'py>) -> PyResult> { + let result = PyList::empty(py); + for (term, coefficient) in self.inner.terms() { + let term = PyTuple::new( + py, + term.iter() + .map(|&inner| Py::new(py, PyFermionicLadder { inner })) + .collect::>>()?, + )?; + result.append((term, coefficient))?; + } + Ok(result) + } + + /// Test whether storage is empty; use equiv for algebraic zero. + fn is_zero(&self) -> bool { + self.inner.is_zero() + } + + /// Add a term in place and return None; errors leave this operator unchanged. + #[pyo3(signature = (term, coefficient=Complex64::new(1.0, 0.0)), text_signature = "($self, term, coefficient=1.0)")] + fn add_term(&mut self, term: &Bound<'_, PyAny>, coefficient: Complex64) -> PyResult<()> { + self.inner + .add_term(ladders(term)?, coefficient) + .map_err(qis_error_to_py_err) + } + + /// Return a conjugate transpose, reversing products and exchanging ladder kinds. + fn adjoint(&self) -> Self { + self.inner.adjoint().into() + } + + /// Return a normal-ordered expansion, including contractions and fermionic signs. + /// Creators precede annihilators; each group uses ascending mode indices. + fn normal_order(&self) -> PyResult { + self.inner + .normal_order() + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Return a scaled copy; the factor and resulting coefficients must be finite. + fn scaled(&self, factor: Complex64) -> PyResult { + self.inner + .scaled(factor) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Explicitly remove coefficients whose complex magnitude is at most atol, in place. + #[pyo3(signature = (*, atol=0.0))] + fn chop(&mut self, atol: f64) -> PyResult<()> { + self.inner.chop(atol).map_err(qis_error_to_py_err) + } + + /// Compare algebraically after normal ordering the difference. + #[pyo3(signature = (other, *, atol=0.0))] + fn equiv(&self, other: &Self, atol: f64) -> PyResult { + self.inner + .equiv(&other.inner, atol) + .map_err(qis_error_to_py_err) + } + + #[pyo3(signature = (*, atol=0.0))] + /// Compare algebraically with the adjoint; atol must be finite and nonnegative. + fn is_hermitian(&self, atol: f64) -> PyResult { + self.inner.is_hermitian(atol).map_err(qis_error_to_py_err) + } + + fn __add__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + match other.extract::>() { + Ok(rhs) => Ok(Py::new( + other.py(), + Self::from( + self.inner + .try_add(&rhs.inner) + .map_err(qis_error_to_py_err)?, + ), + )? + .into_any()), + Err(_) => Ok(other.py().NotImplemented()), + } + } + + fn __sub__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + match other.extract::>() { + Ok(rhs) => Ok(Py::new( + other.py(), + Self::from( + self.inner + .try_sub(&rhs.inner) + .map_err(qis_error_to_py_err)?, + ), + )? + .into_any()), + Err(_) => Ok(other.py().NotImplemented()), + } + } + + fn __mul__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + let result = if let Ok(rhs) = other.extract::>() { + self.inner.try_mul(&rhs.inner) + } else if let Some(factor) = scalar_operand(other)? { + self.inner.scaled(factor) + } else { + return Ok(other.py().NotImplemented()); + }; + Ok(Py::new(other.py(), Self::from(result.map_err(qis_error_to_py_err)?))?.into_any()) + } + + fn __rmul__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + match scalar_operand(other)? { + Some(factor) => Ok(Py::new(other.py(), self.scaled(factor)?)?.into_any()), + None => Ok(other.py().NotImplemented()), + } + } + + fn __neg__(&self) -> PyResult { + self.scaled(Complex64::new(-1.0, 0.0)) + } + + fn __eq__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + match other.extract::>() { + Ok(rhs) => Ok((self.inner == rhs.inner) + .into_pyobject(other.py())? + .to_owned() + .into_any() + .unbind()), + Err(_) => Ok(other.py().NotImplemented()), + } + } + + /// Return an independent copy of this mutable operator. + fn copy(&self) -> Self { + self.clone() + } + fn __copy__(&self) -> Self { + self.copy() + } + fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> Self { + self.copy() + } + + fn __repr__(&self) -> String { + format!( + "FermionicOp(num_modes={}, num_terms={})", + self.num_modes(), + self.num_terms() + ) + } + + fn __str__(&self) -> String { + if self.is_zero() { + return "0".into(); + } + self.inner + .terms() + .map(|(term, coefficient)| { + let product = if term.is_empty() { + "I".into() + } else { + term.iter() + .map(|ladder| match ladder { + FermionicLadder::Create(mode) => format!("a†_{mode}"), + FermionicLadder::Annihilate(mode) => format!("a_{mode}"), + }) + .collect::>() + .join(" ") + }; + format!("({coefficient}) {product}") + }) + .collect::>() + .join(" + ") + } +} + +// Decline foreign types for Python's reflected arithmetic, but propagate numeric errors. +pub(super) fn scalar_operand(value: &Bound<'_, PyAny>) -> PyResult> { + if value.is_instance_of::() + || value.hasattr("__complex__")? + || value.hasattr("__float__")? + || value.hasattr("__index__")? + { + value.extract().map(Some) + } else { + Ok(None) + } +} + +/// Jordan-Wigner encoding: mode p maps to qubit p, with Z factors on modes below p. +#[pyclass(name = "JordanWignerMapper", module = "cqlib.qis.fermion", frozen)] +pub struct PyJordanWignerMapper; + +#[pymethods] +impl PyJordanWignerMapper { + #[new] + fn new() -> Self { + Self + } + + /// Map to a sparse Hamiltonian; non-Hermitian inputs are valid here. + fn map_operator(&self, op: &PyFermionicOp) -> PyResult { + JordanWignerMapper + .map_operator(&op.inner) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Return the register width; Jordan-Wigner uses one qubit per mode. + fn num_qubits(&self, num_modes: &Bound<'_, PyAny>) -> PyResult { + Ok(JordanWignerMapper.num_qubits(index(num_modes, true)?)) + } + + /// bits[p] addresses qubit p (qubit 0 is the least significant bit). + /// Accept only integer or boolean zero/one occupations. Empty input is vacuum. + fn map_occupation(&self, occupation: &Bound<'_, PyAny>) -> PyResult> { + let mut occupations = Vec::new(); + for value in occupation.try_iter()? { + let value = value?; + let integer = integer_index(&value)?; + let bit = if integer.rich_compare(0, CompareOp::Eq)?.is_truthy()? { + 0 + } else if integer.rich_compare(1, CompareOp::Eq)?.is_truthy()? { + 1 + } else { + return Err(PyValueError::new_err("occupations must be zero or one")); + }; + occupations.push(bit); + } + JordanWignerMapper + .map_occupation(&occupations) + .map_err(qis_error_to_py_err) + } + + fn __repr__(&self) -> &'static str { + "JordanWignerMapper()" + } +} + +pub fn register_fermion_module(parent: &Bound<'_, PyModule>) -> PyResult<()> { + let module = PyModule::new(parent.py(), "fermion")?; + module.add_class::()?; + module.add_class::()?; + module.add_class::()?; + parent.add_submodule(&module) +} diff --git a/crates/binding-python/src/qis/hamiltonian.rs b/crates/binding-python/src/qis/hamiltonian.rs index 4ef69645..39d21b75 100644 --- a/crates/binding-python/src/qis/hamiltonian.rs +++ b/crates/binding-python/src/qis/hamiltonian.rs @@ -76,16 +76,6 @@ impl fmt::Display for PyHamiltonian { /// - complex -> complex number /// - tuple (real, imag) -> complex number fn extract_complex(value: &Bound<'_, PyAny>) -> PyResult { - // Try to extract as float first - if let Ok(val) = value.extract::() { - return Ok(Complex64::new(val, 0.0)); - } - // Try to extract as Python complex - if let Ok(py_complex) = value.cast::() { - return Ok(Complex64::new(py_complex.real(), py_complex.imag())); - } - - // Try to extract as tuple (real, imag) if let Ok(tuple) = value.cast::() && tuple.len() == 2 { @@ -94,6 +84,13 @@ fn extract_complex(value: &Bound<'_, PyAny>) -> PyResult { return Ok(Complex64::new(real, imag)); } + // Use the complex protocol before real conversion: NumPy complex scalars + // permit float extraction, but discard the imaginary part with a warning. + // Propagate conversion errors instead of falling back to a lossy float cast. + if let Some(coefficient) = super::fermion::scalar_operand(value)? { + return Ok(coefficient); + } + Err(PyValueError::new_err( "Coefficient must be a float, int, complex, or tuple (real, imag)", )) @@ -188,6 +185,166 @@ impl PyHamiltonian { Ok(Self { inner }) } + /// Construct a validated Pauli sum, absorbing phases and merging duplicates. + /// Only exact zeros are removed. Empty input retains the declared width. + #[staticmethod] + fn from_terms(num_qubits: &Bound<'_, PyAny>, terms: &Bound<'_, PyAny>) -> PyResult { + let width = super::fermion::index(num_qubits, true)?; + let mut parsed = Vec::new(); + for item in terms.try_iter()? { + let item = item?; + let pair = item.cast::()?; + if pair.len() != 2 { + return Err(PyValueError::new_err( + "each term must be (PauliString, coefficient)", + )); + } + let pauli = pair + .get_item(0)? + .extract::>()? + .inner + .clone(); + let coefficient = pair.get_item(1)?.extract::()?; + parsed.push((pauli, coefficient)); + } + Hamiltonian::from_terms(width, parsed) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Return a validated sum with phases absorbed and duplicates merged. + /// Retain all nonzero coefficients; legacy simplify() also truncates small terms. + fn normalized(&self) -> PyResult { + self.inner + .normalized() + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Normalize and project imaginary roundoff <= 1e-10 to zero. + /// Larger imaginary coefficients raise ValueError; all nonzero real terms remain. + fn normalized_hermitian(&self) -> PyResult { + self.inner + .normalized_hermitian() + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Return a validated, merged sum without changing either operand. + /// Legacy + and += concatenate stored terms instead. + fn add(&self, other: &Self) -> PyResult { + self.inner + .try_add(&other.inner) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Return a validated scaled copy, retaining all nonzero coefficients. + /// Unlike legacy scale(), validate the factor and resulting coefficients. + fn scaled(&self, factor: Complex64) -> PyResult { + self.inner + .scaled(factor) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Return the conjugate transpose after absorbing Pauli phases. + fn adjoint(&self) -> PyResult { + self.inner + .adjoint() + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Normalize and remove coefficients with complex magnitude <= atol, in place. + /// Return None; errors leave this Hamiltonian unchanged. + #[pyo3(signature = (*, atol=0.0))] + fn chop(&mut self, atol: f64) -> PyResult<()> { + self.inner.chop(atol).map_err(qis_error_to_py_err) + } + + /// Compare normalized coefficient differences, requiring equal register widths. + /// atol is a coefficient tolerance, not a matrix operator-norm bound. + #[pyo3(signature = (other, *, atol=0.0))] + fn equiv(&self, other: &Self, atol: f64) -> PyResult { + self.inner + .equiv(&other.inner, atol) + .map_err(qis_error_to_py_err) + } + + /// Compare with the adjoint; normalized coefficients satisfy 2*abs(imag) <= atol. + /// This check does not project imaginary parts to zero. + #[pyo3(signature = (*, atol=0.0))] + fn is_hermitian(&self, atol: f64) -> PyResult { + self.inner.is_hermitian(atol).map_err(qis_error_to_py_err) + } + + /// Return self tensor other: other occupies low qubits, self occupies high qubits. + fn tensor(&self, other: &Self) -> PyResult { + self.inner + .tensor(&other.inner) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Embed qubits using mapping[source] = destination; unused targets are identity. + /// Destinations must be unique and in range. This is not a fermionic permutation. + fn remap_qubits( + &self, + mapping: &Bound<'_, PyAny>, + target_width: &Bound<'_, PyAny>, + ) -> PyResult { + let destinations = mapping + .try_iter()? + .map(|v| super::fermion::index(&v?, false)) + .collect::>>()?; + self.inner + .remap_qubits(&destinations, super::fermion::index(target_width, true)?) + .map(Into::into) + .map_err(qis_error_to_py_err) + } + + /// Return a validated difference on the same register, without truncation. + fn __sub__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + match other.extract::>() { + Ok(rhs) => Ok(Py::new( + other.py(), + Self::from( + self.inner + .try_sub(&rhs.inner) + .map_err(qis_error_to_py_err)?, + ), + )? + .into_any()), + Err(_) => Ok(other.py().NotImplemented()), + } + } + + /// Return AB (B acts first) or a scalar multiple; validate and merge the result. + fn __mul__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + let result = if let Ok(rhs) = other.extract::>() { + self.inner.try_mul(&rhs.inner) + } else if let Some(factor) = super::fermion::scalar_operand(other)? { + self.inner.scaled(factor) + } else { + return Ok(other.py().NotImplemented()); + }; + Ok(Py::new(other.py(), Self::from(result.map_err(qis_error_to_py_err)?))?.into_any()) + } + + /// Return a validated scalar multiple. + fn __rmul__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + match super::fermion::scalar_operand(other)? { + Some(factor) => Ok(Py::new(other.py(), self.scaled(factor)?)?.into_any()), + None => Ok(other.py().NotImplemented()), + } + } + + /// Return a validated negation without modifying this operator. + fn __neg__(&self) -> PyResult { + self.scaled(Complex64::new(-1.0, 0.0)) + } + /// Adds a new Pauli string term with a given coefficient to the Hamiltonian. /// /// Args: @@ -195,7 +352,7 @@ impl PyHamiltonian { /// coeff: The coefficient for this term. Can be float, int, complex, or tuple (real, imag). /// /// Returns: - /// self (for method chaining) + /// None. This method modifies the Hamiltonian in place. /// /// Raises: /// ValueError: If the number of qubits in the operator does not match the Hamiltonian. @@ -343,15 +500,18 @@ impl PyHamiltonian { /// >>> h2 = Hamiltonian(2) /// >>> h2.add_term(PauliString.from_str("XX"), 0.3) /// >>> h3 = h1 + h2 # Contains both ZZ and XX terms - fn __add__(&self, other: &PyHamiltonian) -> PyResult { - if self.inner.num_qubits != other.inner.num_qubits { + fn __add__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + let Ok(rhs) = other.extract::>() else { + return Ok(other.py().NotImplemented()); + }; + if self.inner.num_qubits != rhs.inner.num_qubits { return Err(PyValueError::new_err(format!( "Cannot add Hamiltonians with different numbers of qubits: {} vs {}", - self.inner.num_qubits, other.inner.num_qubits + self.inner.num_qubits, rhs.inner.num_qubits ))); } - let result = self.inner.clone() + other.inner.clone(); - Ok(Self { inner: result }) + let result = self.inner.clone() + rhs.inner.clone(); + Ok(Py::new(other.py(), Self { inner: result })?.into_any()) } /// In-place addition of another Hamiltonian. @@ -369,8 +529,15 @@ impl PyHamiltonian { Ok(()) } - fn __eq__(&self, other: &PyHamiltonian) -> bool { - self.inner == other.inner + fn __eq__(&self, other: &Bound<'_, PyAny>) -> PyResult> { + match other.extract::>() { + Ok(rhs) => Ok((self.inner == rhs.inner) + .into_pyobject(other.py())? + .to_owned() + .into_any() + .unbind()), + Err(_) => Ok(other.py().NotImplemented()), + } } fn __str__(&self) -> String { @@ -465,7 +632,21 @@ impl PyHamiltonian { } } + /// Implements Python's shallow-copy protocol with an independent value. + fn __copy__(&self) -> Self { + self.copy() + } + + /// Implements Python's deep-copy protocol; all Rust fields are owned values. + fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> Self { + self.copy() + } + /// Computes the expectation value for a statevector. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. + /// ValueError: If original or merged coefficients are non-finite. fn expectation_statevector(&self, sv: &PyStatevector) -> PyResult { self.inner .expectation_statevector(&sv.inner) @@ -473,6 +654,10 @@ impl PyHamiltonian { } /// Computes the expectation value for a density matrix. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. + /// ValueError: If original or merged coefficients are non-finite. fn expectation_density_matrix(&self, dm: &PyDensityMatrix) -> PyResult { self.inner .expectation_density_matrix(&dm.inner) @@ -480,6 +665,10 @@ impl PyHamiltonian { } /// Computes the expectation value from measurement probabilities. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. + /// ValueError: If original or merged coefficients are non-finite. fn expectation_probs(&self, measurements: &Bound<'_, PyAny>) -> PyResult { let mut rust_measurements = Vec::new(); for item in measurements.try_iter()? { @@ -510,6 +699,10 @@ impl PyHamiltonian { } /// Computes the variance for a statevector. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. + /// ValueError: If original or merged coefficients are non-finite. fn variance_statevector(&self, sv: &PyStatevector) -> PyResult { self.inner .variance_statevector(&sv.inner) diff --git a/crates/binding-python/src/qis/mod.rs b/crates/binding-python/src/qis/mod.rs index 305ef130..daba0b6c 100644 --- a/crates/binding-python/src/qis/mod.rs +++ b/crates/binding-python/src/qis/mod.rs @@ -18,6 +18,7 @@ use pyo3::prelude::*; pub mod entropy; pub mod evolution; +pub mod fermion; pub mod hamiltonian; pub mod metrics; pub mod pauli; @@ -27,7 +28,9 @@ pub mod state; /// Converts a QisError to the appropriate Python exception. pub(crate) fn qis_error_to_py_err(err: QisError) -> PyErr { match err { - QisError::IndexOutOfBounds { .. } => PyIndexError::new_err(err.to_string()), + QisError::IndexOutOfBounds { .. } | QisError::ModeOutOfBounds { .. } => { + PyIndexError::new_err(err.to_string()) + } _ => PyValueError::new_err(err.to_string()), } } @@ -46,6 +49,7 @@ pub fn register_qis_module(parent: &Bound<'_, PyModule>) -> PyResult<()> { qis_module.add_class::()?; qis_module.add_class::()?; qis_module.add_class::()?; + fermion::register_fermion_module(&qis_module)?; // Register state submodule state::register_state_module(&qis_module)?; diff --git a/crates/binding-python/src/qis/pauli.rs b/crates/binding-python/src/qis/pauli.rs index 948631bf..e9157964 100644 --- a/crates/binding-python/src/qis/pauli.rs +++ b/crates/binding-python/src/qis/pauli.rs @@ -507,7 +507,8 @@ impl PyPauliString { /// The expectation value as a float. /// /// Raises: - /// ValueError: If state string length doesn't match num_qubits or contains invalid chars. + /// ValueError: If the Pauli string is not Hermitian, or a state string + /// has the wrong length or contains invalid characters. /// /// Examples: /// >>> ps = PauliString.from_str("IZ") # Z on qubit 0 @@ -527,6 +528,9 @@ impl PyPauliString { } /// Computes the expectation value for a statevector. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. fn expectation_statevector(&self, sv: &PyStatevector) -> PyResult { self.inner .expectation_statevector(&sv.inner) @@ -534,6 +538,9 @@ impl PyPauliString { } /// Computes the expectation value for a density matrix. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. fn expectation_density_matrix(&self, dm: &PyDensityMatrix) -> PyResult { self.inner .expectation_density_matrix(&dm.inner) @@ -541,6 +548,9 @@ impl PyPauliString { } /// Computes the expectation value from measurement probabilities. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. fn expectation_probs(&self, measurements: &Bound<'_, PyAny>) -> PyResult { let mut rust_measurements = Vec::new(); for item in measurements.try_iter()? { @@ -571,6 +581,9 @@ impl PyPauliString { } /// Computes the variance for a statevector. + /// + /// Raises: + /// ValueError: If the observable is not Hermitian or input dimensions differ. fn variance_statevector(&self, sv: &PyStatevector) -> PyResult { self.inner .variance_statevector(&sv.inner) diff --git a/crates/binding-python/src/qis/state/density_matrix.rs b/crates/binding-python/src/qis/state/density_matrix.rs index 44e1b174..d9fef301 100644 --- a/crates/binding-python/src/qis/state/density_matrix.rs +++ b/crates/binding-python/src/qis/state/density_matrix.rs @@ -1,4 +1,5 @@ // This code is part of Cqlib. +// Modified: fix P1 numerical boundaries and simulator error handling. // Modified to support reproducible state sampling. // // (C) Copyright China Telecom Quantum Group 2026 @@ -83,14 +84,17 @@ impl PyDensityMatrix { /// Returns: /// A new DensityMatrix instance in the ground state /// + /// Raises: + /// ValueError: If the dimension is unrepresentable or state allocation fails. + /// /// Examples: /// >>> from cqlib.qis import DensityMatrix /// >>> dm = DensityMatrix(2) # |00><00| state #[new] - fn new(num_qubits: usize) -> Self { - Self { - inner: DensityMatrix::new(num_qubits), - } + fn new(num_qubits: usize) -> PyResult { + Ok(Self { + inner: DensityMatrix::try_new(num_qubits).map_err(qis_error_to_py_err)?, + }) } /// Creates a density matrix from an initial statevector (pure state). @@ -239,10 +243,10 @@ impl PyDensityMatrix { /// >>> dm.probabilities() /// [0.5, 0.5] #[staticmethod] - fn maximally_mixed(num_qubits: usize) -> Self { - Self { - inner: DensityMatrix::maximally_mixed(num_qubits), - } + fn maximally_mixed(num_qubits: usize) -> PyResult { + Ok(Self { + inner: DensityMatrix::try_maximally_mixed(num_qubits).map_err(qis_error_to_py_err)?, + }) } /// Applies a circuit to this density matrix in place. @@ -848,7 +852,8 @@ impl PyDensityMatrix { /// The expectation value as a real number /// /// Raises: - /// ValueError: If the qubit counts don't match or the observable type is invalid + /// ValueError: If qubit counts differ, the observable type is invalid, + /// the observable is not Hermitian, or its coefficients are non-finite. fn expectation(&self, py: Python<'_>, observable: &Bound<'_, PyAny>) -> PyResult { if let Ok(h) = observable.extract::() { py.detach(|| self.inner.expectation(&h.inner)) diff --git a/crates/binding-python/src/qis/state/density_matrix_noise.rs b/crates/binding-python/src/qis/state/density_matrix_noise.rs index 84bfe638..a70358d3 100644 --- a/crates/binding-python/src/qis/state/density_matrix_noise.rs +++ b/crates/binding-python/src/qis/state/density_matrix_noise.rs @@ -81,6 +81,9 @@ impl PyDensityMatrixNoise { /// Returns: /// A new DensityMatrixNoise instance /// + /// Raises: + /// ValueError: If the dimension is unrepresentable or state allocation fails. + /// /// Examples: /// >>> from cqlib.qis.state import DensityMatrixNoise /// >>> # Simulator without noise (ideal simulation) @@ -90,11 +93,11 @@ impl PyDensityMatrixNoise { /// >>> sim = DensityMatrixNoise(2, NoiseModel()) #[new] #[pyo3(signature = (num_qubits, noise_model=None))] - fn new(num_qubits: usize, noise_model: Option) -> Self { + fn new(num_qubits: usize, noise_model: Option) -> PyResult { let model = noise_model.map(|m| m.inner); - Self { - inner: DensityMatrixNoise::new(num_qubits, model), - } + Ok(Self { + inner: DensityMatrixNoise::try_new(num_qubits, model).map_err(qis_error_to_py_err)?, + }) } /// Simulates a circuit, applying noise after each operation. @@ -167,10 +170,17 @@ impl PyDensityMatrixNoise { /// Computes measurement probabilities with readout error modeling. /// /// Args: - /// qubits: Indices of qubits to measure + /// qubits: Storage positions on which to apply readout errors. For a + /// circuit-bound state, noise is looked up using the circuit ID at + /// each position; unbound states use identity IDs. /// /// Returns: - /// A vector of probabilities for all 2^n computational basis states. + /// A vector of probabilities for all 2^num_qubits computational basis + /// states in storage order, independent of the selection order or size. + /// An empty selection applies no readout errors. + /// + /// Raises: + /// IndexError: A position is out of range, even without a noise model. fn probabilities_with_readout(&self, py: Python<'_>, qubits: Vec) -> PyResult> { py.detach(|| self.inner.probabilities_with_readout(&qubits)) .map_err(qis_error_to_py_err) @@ -434,6 +444,10 @@ impl PyDensityMatrixNoise { } /// Computes the expectation value of an observable. + /// + /// Raises: + /// ValueError: If qubit counts differ, the observable type is invalid, + /// the observable is not Hermitian, or its coefficients are non-finite. fn expectation(&self, py: Python<'_>, observable: &Bound<'_, PyAny>) -> PyResult { if let Ok(h) = observable.extract::() { py.detach(|| self.inner.expectation(&h.inner)) diff --git a/crates/binding-python/src/qis/state/statevector.rs b/crates/binding-python/src/qis/state/statevector.rs index 506bb3e7..702769db 100644 --- a/crates/binding-python/src/qis/state/statevector.rs +++ b/crates/binding-python/src/qis/state/statevector.rs @@ -83,14 +83,17 @@ impl PyStatevector { /// Returns: /// A new Statevector instance in the ground state /// + /// Raises: + /// ValueError: If the dimension is unrepresentable or state allocation fails. + /// /// Examples: /// >>> from cqlib.qis import Statevector /// >>> sv = Statevector(2) # |00⟩ state #[new] - fn new(num_qubits: usize) -> Self { - Self { - inner: Statevector::new(num_qubits), - } + fn new(num_qubits: usize) -> PyResult { + Ok(Self { + inner: Statevector::try_new(num_qubits).map_err(qis_error_to_py_err)?, + }) } /// Creates a statevector from initial amplitudes. @@ -194,7 +197,8 @@ impl PyStatevector { /// The expectation value as a real number /// /// Raises: - /// ValueError: If the qubit counts don't match or the observable type is invalid + /// ValueError: If qubit counts differ, the observable type is invalid, + /// the observable is not Hermitian, or its coefficients are non-finite. fn expectation(&self, py: Python<'_>, observable: &Bound<'_, PyAny>) -> PyResult { if let Ok(h) = observable.extract::() { py.detach(|| self.inner.expectation(&h.inner)) diff --git a/crates/binding-python/tests/circuit/test_decompose.py b/crates/binding-python/tests/circuit/test_decompose.py index 668edb6f..7833ecd8 100644 --- a/crates/binding-python/tests/circuit/test_decompose.py +++ b/crates/binding-python/tests/circuit/test_decompose.py @@ -13,6 +13,115 @@ """Decomposition tests for the Python circuit API.""" from cqlib import Circuit, Parameter +from cqlib.qis import DensityMatrix, Statevector +import numpy as np +import pytest + + +@pytest.mark.parametrize( + "width,has_operations", [(0, False), (1, False), (1, True), (2, True)] +) +@pytest.mark.parametrize("repetitions", [0, 1, 2]) +def test_decompose_preserves_global_phase_of_each_definition( + width, has_operations, repetitions +): + inner = Circuit(width) + inner.set_global_phase(0.37) + if has_operations: + inner.x(0) + if width == 2: + inner.cx(0, 1) + gate = inner.to_gate("Phased") + outer = Circuit(2) + outer.set_global_phase(0.12) + expected = Circuit(2) + expected.set_global_phase(0.12 + repetitions * 0.37) + for _ in range(repetitions): + outer.append_circuit_gate(gate, [1, 0][:width]) + if has_operations: + expected.x(1) + if width == 2: + expected.cx(1, 0) + flat = outer.decompose() + assert flat.global_phase.evaluate() == pytest.approx(0.12 + repetitions * 0.37) + for candidate in (outer, flat, flat.decompose()): + np.testing.assert_allclose( + candidate.to_matrix(), expected.to_matrix(), rtol=0, atol=1e-10 + ) + assert len(flat) == len(expected) + assert outer.global_phase.evaluate() == 0.12 + reference_state = expected.to_matrix()[:, 0] + np.testing.assert_allclose( + Statevector.from_circuit(outer).data, reference_state, rtol=0, atol=1e-10 + ) + np.testing.assert_allclose( + DensityMatrix.from_circuit(outer).data, + np.outer(reference_state, reference_state.conj()), + rtol=0, + atol=1e-10, + ) + + +@pytest.mark.parametrize("inverse", [False, True]) +def test_decompose_preserves_nested_symbolic_global_phase(inverse): + theta = Parameter("theta") + inner = Circuit([7, 2]) + inner.set_global_phase(theta / 2) + inner.rx(7, theta) + inner.cx(7, 2) + middle = Circuit([5, 1]) + middle.set_global_phase(theta.sin()) + middle.append_circuit_gate(inner.to_gate("Inner"), [5, 1], [theta + 1]) + outer = Circuit(2) + x = Parameter("x") + outer.set_global_phase(x / 3) + outer.append_circuit_gate(middle.to_gate("Middle"), [1, 0], [2 * x]) + if inverse: + outer = outer.inverse() + flat = outer.decompose() + symbolic = flat.to_symbolic_matrix() + for value in (0.37, -0.61): + phase = value / 3 + np.sin(2 * value) + (2 * value + 1) / 2 + expected = Circuit(2) + expected.set_global_phase(phase) + expected.rx(1, 2 * value + 1) + expected.cx(1, 0) + if inverse: + expected = expected.inverse() + phase = -phase + bindings = {"x": value} + reference = expected.to_matrix() + assert flat.global_phase.evaluate(bindings) == pytest.approx(phase) + for candidate in ( + flat.assign_parameters(bindings), + outer.assign_parameters(bindings).decompose(), + outer.assign_parameters(bindings), + ): + np.testing.assert_allclose( + candidate.to_matrix(), reference, rtol=0, atol=1e-10 + ) + np.testing.assert_allclose( + symbolic.evaluate(bindings), reference, rtol=0, atol=1e-10 + ) + + +def test_decompose_keeps_symbols_used_only_by_global_phase(): + inner = Circuit(1) + inner.set_global_phase(Parameter("theta")) + outer = Circuit(1) + outer.set_global_phase(Parameter("phi")) + outer.append_circuit_gate(inner.to_gate("PhaseOnly"), [0], [2 * Parameter("x")]) + flat = outer.decompose() + assert len(flat) == 0 + assert set(flat.used_symbols) == {"phi", "x"} + bindings = {"phi": 0.12, "x": 0.37} + assert flat.global_phase.evaluate(bindings) == pytest.approx(0.86) + np.testing.assert_allclose( + flat.assign_parameters(bindings).to_matrix(), + np.exp(0.86j) * np.eye(2), + rtol=0, + atol=1e-10, + ) def test_decompose_keeps_standard_gates_unchanged(): diff --git a/crates/binding-python/tests/circuit/test_edge_cases.py b/crates/binding-python/tests/circuit/test_edge_cases.py index 46c83ba1..b23fd02c 100644 --- a/crates/binding-python/tests/circuit/test_edge_cases.py +++ b/crates/binding-python/tests/circuit/test_edge_cases.py @@ -81,3 +81,20 @@ def test_compose_reports_incompatible_mapping(): with pytest.raises(CircuitError): main.compose(other, [0, 2]) + + +@pytest.mark.parametrize("width", [1, 2]) +def test_compose_rejects_duplicate_targets_without_mutation(width): + main = Circuit(width) + main.h(0) + before = main.to_matrix().copy() + other = Circuit(2) + other.cx(0, 1) + + with pytest.raises(CircuitError): + main.compose(other, [0, 0]) + + assert main.num_qubits == width + assert len(main.operations) == 1 + assert np.allclose(main.to_matrix(), before) + assert len(other.operations) == 1 diff --git a/crates/binding-python/tests/circuit/test_instruction_accessors.py b/crates/binding-python/tests/circuit/test_instruction_accessors.py new file mode 100644 index 00000000..b2da7dfd --- /dev/null +++ b/crates/binding-python/tests/circuit/test_instruction_accessors.py @@ -0,0 +1,200 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +""" +Tests for Instruction / ValueInstruction payload accessors. + +Test coverage: +- Predicate/accessor symmetry for every instruction variant +- MCGate / UnitaryGate / CircuitGate payload contents +- ClassicalDataOp payload accessors (kind, target, value, result) +- Parameter ownership: instruction-level gates carry no bound parameters +- Non-matching variants return None +""" + +import pytest + +from cqlib.circuit import ( + Circuit, + ClassicalDataOp, + ClassicalControlOp, + Instruction, + Parameter, + Qubit, + ValueInstruction, + ValueOperation, +) +from cqlib.circuit.gates import Directive, MCGate, RX, StandardGate, UnitaryGate + +# instruction_type -> (predicate property, payload accessor property) +VARIANTS = { + "standard": ("is_standard", "standard_gate"), + "mcgate": ("is_mcgate", "mc_gate"), + "unitary": ("is_unitary", "unitary_gate"), + "circuit": ("is_circuit_gate", "circuit_gate"), + "directive": ("is_directive", "directive"), + "classical_data": ("is_classical_data", "classical_data"), +} + + +def _circuit_gate(): + sub = Circuit(1) + sub.h(0) + return sub.to_gate("h_gate") + + +def _instructions(): + """One Instruction per directly constructible variant.""" + return [ + ("standard", Instruction.from_standard_gate(StandardGate.H)), + ("mcgate", Instruction.from_mc_gate(MCGate(2, StandardGate.X))), + ("unitary", Instruction.from_unitary_gate(UnitaryGate("oracle", 1))), + ("circuit", Instruction.from_circuit_gate(_circuit_gate())), + ("directive", Instruction.from_directive(Directive.barrier())), + ] + + +class TestInstructionAccessorSymmetry: + """Every predicate must pair with a payload accessor that agrees with it.""" + + @pytest.mark.parametrize(("kind", "instruction"), _instructions()) + def test_accessors_agree_with_predicates(self, kind, instruction) -> None: + assert instruction.instruction_type == kind + for other_kind, (predicate, accessor) in VARIANTS.items(): + matching = other_kind == kind + assert getattr(instruction, predicate) is matching + assert (getattr(instruction, accessor) is not None) is matching + + def test_delay_has_no_payload(self) -> None: + instruction = Instruction.delay() + assert instruction.is_delay + for predicate, accessor in VARIANTS.values(): + assert getattr(instruction, predicate) is False + assert getattr(instruction, accessor) is None + + +class TestValueInstructionAccessorSymmetry: + @pytest.mark.parametrize(("kind", "instruction"), _instructions()) + def test_accessors_agree_with_predicates(self, kind, instruction) -> None: + value_instruction = ValueInstruction.from_instruction(instruction) + assert value_instruction.instruction_type == kind + for other_kind, (predicate, accessor) in VARIANTS.items(): + matching = other_kind == kind + assert getattr(value_instruction, predicate) is matching + assert (getattr(value_instruction, accessor) is not None) is matching + + def test_classical_control_has_no_gate_payload(self) -> None: + value_instruction = ValueInstruction.from_classical_control( + ClassicalControlOp.break_() + ) + assert value_instruction.is_classical_control + assert value_instruction.classical_control is not None + for predicate, accessor in VARIANTS.values(): + assert getattr(value_instruction, predicate) is False + assert getattr(value_instruction, accessor) is None + + +class TestMcGatePayload: + def test_payload_contents(self) -> None: + instruction = Instruction.from_mc_gate(MCGate(2, StandardGate.RZ)) + gate = instruction.mc_gate + assert gate is not None + assert gate.num_ctrl_qubits == 2 + assert gate.base_gate == StandardGate.RZ + assert gate.num_qubits == 3 + + def test_payload_carries_no_bound_parameters(self) -> None: + """Parameters belong to the operation, not to the instruction.""" + theta = Parameter("theta") + operation = ValueOperation.from_mc_gate( + MCGate(1, RX(theta)), [Qubit(0), Qubit(1)] + ) + instruction = operation.instruction + assert instruction.is_mcgate + gate = instruction.mc_gate + assert gate is not None + assert gate.params == [] + assert operation.params == [theta] + + +class TestUnitaryGatePayload: + def test_payload_contents(self) -> None: + instruction = Instruction.from_unitary_gate(UnitaryGate("oracle", 2)) + gate = instruction.unitary_gate + assert gate is not None + assert gate.label == "oracle" + assert gate.num_qubits == 2 + + +class TestCircuitGatePayload: + def test_payload_contents(self) -> None: + instruction = Instruction.from_circuit_gate(_circuit_gate()) + gate = instruction.circuit_gate + assert gate is not None + assert gate.name == "h_gate" + assert gate.num_qubits == 1 + + +class TestDirectivePayload: + def test_payload_contents(self) -> None: + instruction = Instruction.from_directive(Directive.measure()) + directive = instruction.directive + assert directive is not None + assert str(directive) == "measure" + + +class TestClassicalDataPayload: + def test_value_instruction_payload(self) -> None: + circuit = Circuit(1) + circuit.measure(0) + instruction = circuit.operations[0].instruction + assert instruction.is_classical_data + data = instruction.classical_data + assert isinstance(data, ClassicalDataOp) + assert data.kind == "measure_bit" + assert data.result is not None + assert data.target is None + assert data.value is None + + def test_storage_instruction_payload(self) -> None: + circuit = Circuit(2) + circuit.measure_bits([0, 1]) + value_instruction = circuit.operations[0].instruction + instruction = value_instruction.instruction + assert instruction is not None + assert instruction.is_classical_data + data = instruction.classical_data + assert data is not None + assert data.kind == "measure_bits" + assert data.result is not None + + def test_store_payload(self) -> None: + circuit = Circuit(1) + measurement = circuit.measure(0) + target = circuit.var(measurement.ty) + circuit.store(target, measurement.expr()) + instruction = circuit.operations[1].instruction + assert instruction.is_classical_data + data = instruction.classical_data + assert data is not None + assert data.kind == "store" + assert data.target is not None + assert data.value is not None + assert data.result is None + + +class TestClassicalDataSubmodule: + def test_runtime_submodule_matches_stub(self) -> None: + import cqlib.circuit.classical_data as submodule + + assert submodule.ClassicalDataOp is ClassicalDataOp + assert submodule.__all__ == ["ClassicalDataOp"] diff --git a/crates/binding-python/tests/compile/test_commutation.py b/crates/binding-python/tests/compile/test_commutation.py index 4eb5692c..4696ad8e 100644 --- a/crates/binding-python/tests/compile/test_commutation.py +++ b/crates/binding-python/tests/compile/test_commutation.py @@ -17,6 +17,7 @@ import pytest from cqlib.circuit import ( + Circuit, Instruction, Parameter, Qubit, @@ -64,6 +65,46 @@ def test_builtin_checker_proves_exact_and_global_phase_commutation(): assert "Parameter(" in repr(global_phase) +@pytest.mark.parametrize("order", [[0, 1], [1, 0], [7, 2]]) +@pytest.mark.parametrize("parameterized", [False, True]) +def test_circuit_gate_matrix_commutation_uses_positional_targets(order, parameterized): + body = Circuit(order) + body.rx(order[0], Parameter("theta") if parameterized else 0.37) + circuit = Circuit(2) + circuit.append_circuit_gate( + body.to_gate("first_rx"), [0, 1], [0.37] if parameterized else [] + ) + matrix_checker = CommutationChecker.with_config( + CommutationConfig(enable_rule_oracle=False, enable_matrix_fallback=True) + ) + for target in (0, 1): + z = operation(StandardGate.Z, [target]) + expected = None if target == 0 else Commutation.exact() + for lhs, rhs in ((circuit[0], z), (z, circuit[0])): + assert check_commutation(lhs, rhs) == expected + assert matrix_checker.check(lhs, rhs) == expected + + +def test_circuit_gate_matrix_commutation_preserves_global_phase_proof(): + body = Circuit([7, 2]) + body.x(7) + circuit = Circuit(2) + circuit.append_circuit_gate(body.to_gate("first_x"), [0, 1]) + z = operation(StandardGate.Z, [0]) + for lhs, rhs in ((circuit[0], z), (z, circuit[0])): + proof = check_commutation(lhs, rhs) + assert proof is not None and not proof.is_exact() + assert math.isclose(abs(proof.phase.evaluate()), math.pi, abs_tol=1e-12) + + +def test_circuit_gate_unresolved_matrix_does_not_produce_a_proof(): + body = Circuit(2) + body.rx(0, Parameter("theta")) + circuit = Circuit(2) + circuit.append_circuit_gate(body.to_gate("symbolic"), [0, 1], [Parameter("x")]) + assert check_commutation(circuit[0], operation(StandardGate.Z, [0])) is None + + def test_symbolic_parameters_are_preserved_for_algebraic_proofs(): lhs = operation(StandardGate.RZ(Parameter("a")), [0]) rhs = operation(StandardGate.RZ(Parameter("b")), [0]) diff --git a/crates/binding-python/tests/compile/transform/test_block_zxz.py b/crates/binding-python/tests/compile/transform/test_block_zxz.py new file mode 100644 index 00000000..0bae0d4f --- /dev/null +++ b/crates/binding-python/tests/compile/transform/test_block_zxz.py @@ -0,0 +1,479 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +import concurrent.futures +import copy + +import numpy as np +import pytest + +from cqlib.circuit import Circuit, Instruction, StandardGate, UnitaryGate +from cqlib.compile import CompilerConfigError, compile +from cqlib.compile.transform.decompose import ( + UnitaryDecomposeConfig, + decompose_unitaries, + decompose_unitaries_with_rule_stats, +) +from cqlib.compile.transform.decompose.block_zxz import ( + BlockZxzDecomposeOptions, + decompose_block_zxz, + decompose_block_zxz_with_options, +) +from cqlib.device import Device + + +def random_unitary(dim: int, seed: int) -> np.ndarray: + rng = np.random.default_rng(seed) + shape = (dim, dim) + z = rng.normal(size=shape) + 1j * rng.normal(size=shape) + return np.linalg.qr(z)[0] * np.exp(0.321j) + + +@pytest.mark.parametrize( + "matrix", [np.roll(np.eye(8), 1, axis=0), random_unitary(32, 13)] +) +def test_block_zxz_preserves_global_phase(matrix: np.ndarray) -> None: + n = (len(matrix) - 1).bit_length() + source = Circuit(n) + source.append_unitary_gate( + UnitaryGate("phase", n).with_matrix(matrix), list(reversed(range(n))) + ) + for circuit in (decompose_block_zxz(matrix), decompose_unitaries(source).circuit): + actual = circuit.to_matrix() + phase = np.angle(np.vdot(matrix, actual)) + np.testing.assert_allclose( + actual, + matrix, + rtol=0, + atol=1e-10, + err_msg=f"Relative phase {phase:.6g} rad", + ) + + +def test_explicit_options_and_strided_input() -> None: + matrix = random_unitary(8, 7)[::-1, ::-1] + for options, expected_cx in [(None, 19), (BlockZxzDecomposeOptions.none(), 24)]: + c = decompose_block_zxz_with_options(matrix, options=options) + assert sum(op.instruction.name == "CX" for op in c.operations) == expected_cx + np.testing.assert_allclose(c.to_matrix(), matrix, rtol=0, atol=1e-10) + + +@pytest.mark.parametrize( + "matrix", + [ + np.zeros((2, 3)), + np.eye(3), + np.zeros((8, 8)), + [[np.nan, 0], [0, 1]], + [[1, 0], [0, np.inf]], + ], +) +def test_invalid_matrix(matrix: object) -> None: + with pytest.raises(CompilerConfigError): + decompose_block_zxz(matrix) + + +@pytest.mark.parametrize("atol", [-1, np.nan, np.inf]) +def test_invalid_tolerance(atol: float) -> None: + with pytest.raises(CompilerConfigError): + decompose_block_zxz_with_options(np.eye(8), atol) + + +def test_block_zxz_through_device_workflow() -> None: + matrix = random_unitary(8, 7) + body = Circuit(3) + body.append_unitary_gate( + UnitaryGate("asymmetric", 3).with_matrix(matrix), [2, 0, 1] + ) + source = Circuit(3) + source.append_circuit_gate(body.to_gate("nested"), [0, 1, 2]) + device = Device.bidirectional_line("block-zxz", 3) + device.native_gates = [ + Instruction.from_standard_gate(g) for g in (StandardGate.U, StandardGate.CX) + ] + result = compile(source, device=device, seed=17) + assert result.step_changed("decompose.definitions") + assert result.step_changed("decompose.unitary") + assert result.step("route.sabre") is not None + assert {op.instruction.name for op in result.circuit.operations} == {"U", "CX"} + metadata = result.device_metadata + assert metadata is not None + + # Routing permutes the input columns and output rows independently. + def physical_indices(layout): + return [ + sum(((i >> j) & 1) << layout.get_physical(j).id for j in range(3)) + for i in range(8) + ] + + indices = np.ix_( + physical_indices(metadata.final_layout), + physical_indices(metadata.initial_layout), + ) + np.testing.assert_allclose( + result.circuit.to_matrix()[indices], source.to_matrix(), rtol=0, atol=1e-10 + ) + + +def test_nearly_scalar_spectrum() -> None: + # Sixteen phases occupy an interval of 0.015 radians. The 1e-10 + # matrix budget is seven orders below their nearest-neighbor spacing. + basis = random_unitary(16, 27) + phases = 0.37 + 0.001 * np.arange(16) + matrix = (basis * np.exp(1j * phases)) @ basis.conj().T + np.testing.assert_allclose( + decompose_block_zxz(matrix).to_matrix(), matrix, rtol=0, atol=1e-10 + ) + + +def test_decompose_package_reexports_direct_entry_points() -> None: + from cqlib.compile.transform import decompose + + assert decompose.decompose_block_zxz is decompose_block_zxz + assert ( + decompose.decompose_block_zxz_with_options is decompose_block_zxz_with_options + ) + assert decompose.BlockZxzDecomposeOptions is BlockZxzDecomposeOptions + + +def test_nearly_degenerate_two_qubit_leaf() -> None: + fourier = np.fft.fft(np.eye(4)) / 2 + spectrum = np.exp(1e-8j * np.array([0, 1, 3, 7])) + unitary = ((fourier * spectrum) @ fourier.conj().T)[[0, 1, 3, 2]] + np.testing.assert_allclose( + decompose_block_zxz(unitary).to_matrix(), unitary, atol=1e-10, rtol=0 + ) + + +def test_options_value_semantics() -> None: + default_a = BlockZxzDecomposeOptions() + default_b = BlockZxzDecomposeOptions(opt_a1=True, opt_a2=True, opt_a2_force=False) + none_opts = BlockZxzDecomposeOptions.none() + + assert default_a == default_b + assert hash(default_a) == hash(default_b) + assert default_a != none_opts + assert len({default_a, default_b, none_opts}) == 2 + assert ( + repr(default_a) + == "BlockZxzDecomposeOptions(opt_a1=True, opt_a2=True, opt_a2_force=False)" + ) + assert ( + repr(none_opts) + == "BlockZxzDecomposeOptions(opt_a1=False, opt_a2=False, opt_a2_force=False)" + ) + assert copy.copy(default_a) == default_a + assert copy.deepcopy(default_a) == default_a + + with pytest.raises(AttributeError): + default_a.opt_a1 = False # type: ignore[misc] + with pytest.raises(TypeError): + BlockZxzDecomposeOptions(True, True, False) # type: ignore[misc] + + +def test_array_input_layouts_dtypes_and_invalid_shapes() -> None: + u = random_unitary(8, 29) + read_only = u.copy() + read_only.setflags(write=False) + padded = np.zeros((16, 16), dtype=np.complex128) + padded[::2, ::2] = u + + for candidate in ( + np.asfortranarray(u), + u.T, + padded[::2, ::2], + read_only, + u.tolist(), + np.eye(8, dtype=np.float64), + np.eye(8, dtype=np.int64), + np.eye(8, dtype=np.complex64), + ): + expected = np.asarray(candidate, dtype=np.complex128) + np.testing.assert_allclose( + decompose_block_zxz(candidate).to_matrix(), expected, rtol=0, atol=1e-10 + ) + + for bad_type in (1.0, np.ones(8), np.zeros((2, 2, 2)), None): + with pytest.raises(TypeError): + decompose_block_zxz(bad_type) # type: ignore[arg-type] + for bad_dim in (np.empty((0, 0)), np.eye(1), np.eye(6)): + with pytest.raises(CompilerConfigError): + decompose_block_zxz(bad_dim) + + +def test_adversarial_demux_spectra_and_loose_atol() -> None: + v4 = random_unitary(4, 31) + l1 = random_unitary(4, 32) + l2 = random_unitary(4, 33) + for gap in (1.5e-8, 2e-8, 5e-8, 1e-7): + phases = np.array( + [np.pi / 2, -np.pi / 2 + gap, np.pi / 4, -3 * np.pi / 4 + gap] + ) + c_mat = (v4 * np.exp(-1j * phases)) @ v4.conj().T + uy = 1j * c_mat + s, cs = np.sin(0.63), np.cos(0.63) + dense = np.block([[cs * l1, s * (l1 @ uy)], [-s * l2, cs * (l2 @ uy)]]) + np.testing.assert_allclose( + decompose_block_zxz(dense, atol=1e-10).to_matrix(), + dense, + rtol=0, + atol=1e-10, + ) + + for dim, seed in ((2, 41), (4, 42), (8, 43), (16, 44)): + exact = random_unitary(dim, seed) + noisy = exact * (1.0 + 2e-7) + actual = decompose_block_zxz(noisy, atol=1e-5).to_matrix() + np.testing.assert_allclose(actual, noisy, rtol=0, atol=1e-5) + + +def test_overlapping_permuted_cache_and_cz_device_compile() -> None: + u3 = random_unitary(8, 51) + gate3 = UnitaryGate("u3", 3).with_matrix(u3) + qc = Circuit(5) + for qargs in ([0, 1, 2], [1, 2, 0], [2, 0, 1], [4, 1, 3]): + qc.append_unitary_gate(gate3, qargs) + res, stats = decompose_unitaries_with_rule_stats(qc) + assert (stats.hits, stats.misses, stats.inserts) == (3, 1, 1) + np.testing.assert_allclose( + res.circuit.to_matrix(), qc.to_matrix(), rtol=0, atol=1e-9 + ) + + u4 = random_unitary(16, 52) + src = Circuit(4) + src.append_unitary_gate(UnitaryGate("u4", 4).with_matrix(u4), [2, 0, 3, 1]) + device = Device.bidirectional_line("cz-4q", 4) + device.native_gates = [ + Instruction.from_standard_gate(g) + for g in (StandardGate.RZ, StandardGate.X2P, StandardGate.CZ) + ] + compiled = compile(src, device=device, seed=19) + assert {op.instruction.name for op in compiled.circuit.operations}.issubset( + {"RZ", "X2P", "CZ"} + ) + metadata = compiled.device_metadata + assert metadata is not None + + def physical_indices(layout): + return [ + sum(((i >> j) & 1) << layout.get_physical(j).id for j in range(4)) + for i in range(16) + ] + + indices = np.ix_( + physical_indices(metadata.final_layout), + physical_indices(metadata.initial_layout), + ) + np.testing.assert_allclose( + compiled.circuit.to_matrix()[indices], src.to_matrix(), rtol=0, atol=1e-9 + ) + + +def test_concurrent_block_zxz_synthesis() -> None: + def run_one(seed: int) -> float: + u = random_unitary(16, seed) + c = decompose_block_zxz(u) + return float(np.max(np.abs(c.to_matrix() - u))) + + with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: + errors = list(executor.map(run_one, range(60, 68))) + assert max(errors) <= 1e-10 + + +def test_unitary_decompose_config_block_zxz_options() -> None: + default_cfg = UnitaryDecomposeConfig() + assert default_cfg.block_zxz_options == BlockZxzDecomposeOptions() + assert "block_zxz_options" not in repr(default_cfg) + + unopt_cfg = UnitaryDecomposeConfig( + block_zxz_options=BlockZxzDecomposeOptions.none() + ) + assert unopt_cfg.block_zxz_options == BlockZxzDecomposeOptions.none() + assert unopt_cfg != default_cfg + rebuilt = eval( + repr(unopt_cfg), + { + "UnitaryDecomposeConfig": UnitaryDecomposeConfig, + "BlockZxzDecomposeOptions": BlockZxzDecomposeOptions, + }, + ) + assert rebuilt == unopt_cfg + + u3 = random_unitary(8, 7) + qc = Circuit(3) + qc.append_unitary_gate(UnitaryGate("u3", 3).with_matrix(u3), [2, 1, 0]) + opt_circuit = decompose_unitaries(qc, default_cfg).circuit + unopt_circuit = decompose_unitaries(qc, unopt_cfg).circuit + assert sum(op.instruction.name == "CX" for op in opt_circuit.operations) == 19 + assert sum(op.instruction.name == "CX" for op in unopt_circuit.operations) == 24 + np.testing.assert_allclose(opt_circuit.to_matrix(), u3, rtol=0, atol=1e-10) + np.testing.assert_allclose(unopt_circuit.to_matrix(), u3, rtol=0, atol=1e-10) + + +def test_strided_non_element_multiple_and_unaligned_complex128_arrays() -> None: + hadamard = np.array([[1, 1], [1, -1]], dtype=np.complex128) / np.sqrt(2) + + # 8-byte aligned complex128 array with 40-byte row stride (not a multiple of 16). + backing = np.zeros(12, dtype=np.float64) + strided = np.lib.stride_tricks.as_strided( + backing.view(np.complex128), shape=(2, 2), strides=(40, 16) + ) + strided[...] = hadamard + assert strided.flags.aligned + assert strided.strides == (40, 16) + np.testing.assert_allclose( + decompose_block_zxz(strided).to_matrix(), hadamard, rtol=0, atol=1e-10 + ) + + # Unaligned but C-contiguous complex128 view (1-byte offset inside a raw buffer). + raw = bytearray(128) + unaligned = np.ndarray(shape=(2, 2), dtype=np.complex128, buffer=raw, offset=1) + unaligned[...] = hadamard + assert unaligned.flags.c_contiguous + assert not unaligned.flags.aligned + np.testing.assert_allclose( + decompose_block_zxz(unaligned).to_matrix(), hadamard, rtol=0, atol=1e-10 + ) + + +def test_repeated_weak_xx_interaction_does_not_accumulate_dropped_rotation() -> None: + from cqlib.compile.transform.decompose import TwoQubitUnitaryDecomposeBasis + from cqlib.compile.transform.decompose.unitary import synthesize_numeric_2q_unitary + + angle = 9e-11 + u2 = np.zeros((4, 4), dtype=np.complex128) + for i in range(4): + u2[i, i] = np.cos(angle) + u2[i, i ^ 3] = 1j * np.sin(angle) + for basis in ( + TwoQubitUnitaryDecomposeBasis.cx(), + TwoQubitUnitaryDecomposeBasis.cy(), + TwoQubitUnitaryDecomposeBasis.cz(), + ): + synth = synthesize_numeric_2q_unitary(u2, 1, 0, basis) + entanglers = sum( + op.instruction.name in {"CX", "CY", "CZ"} for op in synth.operations + ) + assert entanglers == 2 + + def weak_3q(theta: float) -> np.ndarray: + out = np.zeros((8, 8), dtype=np.complex128) + for i in range(8): + out[i, i] = np.cos(theta) + out[i, i ^ 3] = 1j * np.sin(theta) + return out + + for weak_angle, repeats in ((9e-11, 64), (8e-13, 512)): + gate = UnitaryGate("weak_xx", 3).with_matrix(weak_3q(weak_angle)) + qc = Circuit(3) + for _ in range(repeats): + qc.append_unitary_gate(gate, [2, 1, 0]) + expected = weak_3q(weak_angle * repeats) + + np.testing.assert_allclose( + decompose_unitaries(qc).circuit.to_matrix(), expected, rtol=0, atol=1e-10 + ) + np.testing.assert_allclose( + compile(qc).circuit.to_matrix(), expected, rtol=0, atol=1e-10 + ) + + +def test_near_tolerance_unitary_boundary_decomposes_and_compiles() -> None: + rng = np.random.default_rng(7) + base = random_unitary(8, 7) + scaled = base * (1.0 + 4.5e-11) + + noise = rng.normal(size=(8, 8)) + 1j * rng.normal(size=(8, 8)) + probe = base + noise * 1e-11 + probe_err = float(np.max(np.abs(probe.conj().T @ probe - np.eye(8)))) + anisotropic = base + noise * (1e-11 * (9e-11 / probe_err)) + + # Row-scaled QFT has Gram error <= 1e-10 while polar max-entry shift > 1e-10. + idx = np.arange(8) + qft = np.exp(2j * np.pi * np.outer(idx, idx) / 8) / np.sqrt(8) + polar_shift = qft.copy() + polar_shift[0, :] *= 1.0 + 3.6e-10 + + for matrix in (scaled, anisotropic, polar_shift): + unitarity_err = float(np.max(np.abs(matrix.conj().T @ matrix - np.eye(8)))) + assert 8e-11 < unitarity_err < 1e-10 + u_svd, _, vh_svd = np.linalg.svd(matrix) + projected = u_svd @ vh_svd + + gate = UnitaryGate("near_tol", 3).with_matrix(matrix) + np.testing.assert_allclose( + decompose_block_zxz(matrix, atol=1e-10).to_matrix(), + projected, + rtol=0, + atol=1e-10, + ) + qc = Circuit(3) + qc.append_unitary_gate(gate, [2, 1, 0]) + np.testing.assert_allclose( + decompose_unitaries(qc).circuit.to_matrix(), projected, rtol=0, atol=1e-10 + ) + np.testing.assert_allclose( + compile(qc).circuit.to_matrix(), projected, rtol=0, atol=1e-10 + ) + + # 64x64 coherent rank-1 perturbation below 64*n*eps in max-entry Gram norm. + n = 64 + gram_noise = 0.94 * 64 * n * np.finfo(float).eps + p = gram_noise / (np.sqrt(1.0 + n * gram_noise) + 1.0) + coherent = np.eye(n, dtype=np.complex128) + p * np.ones((n, n), dtype=np.complex128) + u_svd, _, vh_svd = np.linalg.svd(coherent) + coherent_proj = u_svd @ vh_svd + np.testing.assert_allclose( + decompose_block_zxz(coherent, atol=1e-10).to_matrix(), + coherent_proj, + rtol=0, + atol=1e-10, + ) + + +def test_nine_qubit_dense_wide_arc_spectrum_decomposes() -> None: + rng = np.random.default_rng(777) + z = rng.normal(size=(256, 256)) + 1j * rng.normal(size=(256, 256)) + v, _ = np.linalg.qr(z) + phases = np.linspace(-1.2, 1.2, 256) + u = np.block( + [ + [(v * np.exp(1j * phases)) @ v.conj().T, np.zeros((256, 256))], + [np.zeros((256, 256)), np.eye(256)], + ] + ) + + circuit = decompose_block_zxz(u, 1e-10) + assert circuit.num_qubits == 9 + assert len(circuit.operations) > 0 + + psi = rng.normal(size=512) + 1j * rng.normal(size=512) + psi /= np.linalg.norm(psi) + state = psi.reshape([2] * 9).copy() + for op in circuit.operations: + qs = [q.index for q in op.qubits] + if op.instruction.name == "CX": + c, t = 8 - qs[0], 8 - qs[1] + idx0 = [slice(None)] * 9 + idx1 = [slice(None)] * 9 + idx0[c], idx0[t] = 1, 0 + idx1[c], idx1[t] = 1, 1 + tmp = state[tuple(idx0)].copy() + state[tuple(idx0)] = state[tuple(idx1)] + state[tuple(idx1)] = tmp + else: + ax = 8 - qs[0] + state = np.tensordot(op.matrix(), state, axes=([1], [ax])) + state = np.moveaxis(state, 0, ax) + phase = float(str(circuit.global_phase)) + actual = state.reshape(-1) * np.exp(1j * phase) + np.testing.assert_allclose(actual, u @ psi, rtol=0, atol=1e-10) diff --git a/crates/binding-python/tests/compile/transform/test_decompose.py b/crates/binding-python/tests/compile/transform/test_decompose.py index 106606f0..b3ee211b 100644 --- a/crates/binding-python/tests/compile/transform/test_decompose.py +++ b/crates/binding-python/tests/compile/transform/test_decompose.py @@ -51,6 +51,141 @@ def operation_names(circuit: Circuit) -> list[str]: return [operation.instruction.instruction.name for operation in circuit.operations] +@pytest.fixture +def weyl_boundary_matrix() -> np.ndarray: + # Preserve the reported matrix, including its floating-point roundoff. + return np.array( + [ + [ + complex(-0.14755155196621783, 0.08535345227001921), + complex(-0.015112015359785388, -0.026124324914469213), + complex(-4.3021142204224816e-16, 0.06601980439593577), + complex(-0.9826870609532827, 2.7755575615628914e-16), + ], + [ + complex(-0.006212290419590961, -0.010739262071974568), + complex(-0.3589338503302527, 0.2076307761864266), + complex(0.9070757873156866, -5.412337245047638e-16), + complex(-6.245004513516506e-16, -0.07152302867497204), + ], + [ + complex(-0.9706933646378622, 2.7755575615628914e-17), + complex(2.6020852139652106e-18, -0.15594957493615416), + complex(0.03569705171577718, -0.061709927849413246), + complex(0.1457506851638859, 0.08431171332109447), + ], + [ + complex(7.112366251504909e-17, -0.16894909068671718), + complex(-0.8960049266516804, -3.608224830031759e-16), + complex(-0.35455306241796475, -0.20509664240745978), + complex(-0.014674445936026376, 0.02536789332498595), + ], + ], + dtype=np.complex128, + ) + + +def reconstructed_kak(decomposition: KakDecomposition) -> np.ndarray: + core = np.eye(4, dtype=np.complex128) + paulis = ( + np.array([[0, 1], [1, 0]], dtype=np.complex128), + np.array([[0, -1j], [1j, 0]], dtype=np.complex128), + np.diag([1, -1]), + ) + for angle, pauli in zip( + (decomposition.a, decomposition.b, decomposition.c), paulis, strict=True + ): + core = core @ ( + np.cos(angle) * np.eye(4) + 1j * np.sin(angle) * np.kron(pauli, pauli) + ) + return ( + np.exp(1j * decomposition.global_phase) + * np.kron(decomposition.k1l, decomposition.k1r) + @ core + @ np.kron(decomposition.k2l, decomposition.k2r) + ) + + +@pytest.mark.parametrize("phase", [0.0, -1.1, np.pi / 4, np.pi / 2, np.pi, 2.7]) +def test_weyl_boundary_kak_preserves_phase_and_su2_factors( + weyl_boundary_matrix: np.ndarray, phase: float +) -> None: + source = np.exp(1j * phase) * weyl_boundary_matrix + decomposition = kak_decompose(source) + assert decomposition.a == np.pi / 4 + assert decomposition.c > 0 + np.testing.assert_allclose( + reconstructed_kak(decomposition), source, atol=1e-12, rtol=0 + ) + for factor in ( + decomposition.k1l, + decomposition.k1r, + decomposition.k2l, + decomposition.k2r, + ): + np.testing.assert_allclose( + factor.conj().T @ factor, np.eye(2), atol=1e-12, rtol=0 + ) + np.testing.assert_allclose(np.linalg.det(factor), 1, atol=1e-12, rtol=0) + + +@pytest.mark.parametrize( + "basis", + [ + TwoQubitUnitaryDecomposeBasis.cx(), + TwoQubitUnitaryDecomposeBasis.cy(), + TwoQubitUnitaryDecomposeBasis.cz(), + TwoQubitUnitaryDecomposeBasis.rzz(), + TwoQubitUnitaryDecomposeBasis.pauli_rotations(), + ], +) +@pytest.mark.parametrize("qubits", [[0, 1], [1, 0]]) +def test_weyl_boundary_synthesis_and_cached_unitary_lowering( + weyl_boundary_matrix: np.ndarray, + basis: TwoQubitUnitaryDecomposeBasis, + qubits: list[int], +) -> None: + matrix = np.exp(0.37j) * weyl_boundary_matrix + gate = UnitaryGate("boundary", 2).with_matrix(matrix) + source = Circuit(2) + source.append_unitary_gate(gate, qubits) + synthesis = synthesize_numeric_2q_unitary(matrix, *qubits, basis) + output = Circuit.from_operations([Qubit(0), Qubit(1)], synthesis.operations) + output.set_global_phase(synthesis.global_phase) + np.testing.assert_allclose( + output.to_matrix(), source.to_matrix(), atol=1e-9, rtol=0 + ) + + source.append_unitary_gate(gate, qubits) + config = UnitaryDecomposeConfig(two_qubit_basis=basis) + result, stats = decompose_unitaries_with_rule_stats(source, config) + np.testing.assert_allclose( + result.circuit.to_matrix(), source.to_matrix(), atol=1e-9, rtol=0 + ) + assert (stats.hits, stats.misses, stats.inserts) == (1, 1, 1) + + +def test_weyl_boundary_interior_negative_c_is_not_rejected() -> None: + identity = np.eye(4, dtype=np.complex128) + x = np.array([[0, 1], [1, 0]], dtype=np.complex128) + y = np.array([[0, -1j], [1j, 0]], dtype=np.complex128) + z = np.diag([1, -1]) + for distance in (1e-12, 1e-10, 5e-9, 2e-8): + source = identity.copy() + for angle, pauli in zip( + (np.pi / 4 - distance, 0.2, -0.03), (x, y, z), strict=True + ): + source = source @ ( + np.cos(angle) * identity + 1j * np.sin(angle) * np.kron(pauli, pauli) + ) + decomposition = kak_decompose(source) + assert decomposition.a < np.pi / 4 + assert decomposition.c < 0 + np.testing.assert_allclose( + reconstructed_kak(decomposition), source, atol=1e-12, rtol=0 + ) + + def test_decompose_module_and_types_are_registered() -> None: assert "cqlib._native.compile.transform.decompose" in sys.modules assert decompose.expand_definitions is expand_definitions @@ -259,23 +394,7 @@ def test_kak_decomposition_reconstructs_matrix_and_returns_owned_arrays() -> Non ) decomposition = kak_decompose(source) - identity = np.eye(4, dtype=np.complex128) - x = np.array([[0, 1], [1, 0]], dtype=np.complex128) - y = np.array([[0, -1j], [1j, 0]], dtype=np.complex128) - z = np.array([[1, 0], [0, -1]], dtype=np.complex128) - xx, yy, zz = np.kron(x, x), np.kron(y, y), np.kron(z, z) - cartan = ( - np.cos(decomposition.a) * identity + 1j * np.sin(decomposition.a) * xx - ) @ (np.cos(decomposition.b) * identity + 1j * np.sin(decomposition.b) * yy) - cartan = cartan @ ( - np.cos(decomposition.c) * identity + 1j * np.sin(decomposition.c) * zz - ) - reconstructed = ( - np.exp(1j * decomposition.global_phase) - * np.kron(decomposition.k1l, decomposition.k1r) - @ cartan - @ np.kron(decomposition.k2l, decomposition.k2r) - ) + reconstructed = reconstructed_kak(decomposition) np.testing.assert_allclose(reconstructed, source, atol=1e-7) local = decomposition.k1l diff --git a/crates/binding-python/tests/error_mitigation/test_pipeline.py b/crates/binding-python/tests/error_mitigation/test_pipeline.py index d8fb499b..f3ee6498 100644 --- a/crates/binding-python/tests/error_mitigation/test_pipeline.py +++ b/crates/binding-python/tests/error_mitigation/test_pipeline.py @@ -34,6 +34,20 @@ def single_x_circuit() -> Circuit: return circuit +def is_numerator_observable(observable: Hamiltonian) -> bool: + """Distinguish VD numerator from denominator observables by content. + + The denominator observable is a single X on the ancillary (last) qubit; + the numerator also carries non-identity Paulis on the first copy's + qubits. + """ + return any( + qubit < observable.num_qubits - 1 + for term, _coefficient in observable.terms + for qubit in term.support() + ) + + def test_error_mitigation_public_exports_and_estimator_aliases() -> None: assert em.ZNEMitigation.__module__ == "cqlib.error_mitigation" assert em.ErrorMitigation.__module__ == "cqlib.error_mitigation" @@ -122,10 +136,10 @@ def test_virtual_distillation_copy_swap_and_run_paths() -> None: vd = em.VirtualDistillation(circuit, 2) copy_swap = vd.build_copy_swap_circuit() - assert copy_swap.width == 2 + assert copy_swap.width == 3 assert [ operation.instruction.instruction.name for operation in copy_swap.operations - ] == ["SWAP"] + ] == ["H", "C1-SWAP"] calls: list[tuple[int, int | None, bool]] = [] @@ -134,10 +148,16 @@ def estimator( observable: Hamiltonian | None, shots: int | None, ) -> tuple[float, float]: - calls.append((run_circuit.width, shots, observable is None)) - if observable is None: - return (2.0, 1.0) - return (1.5, 0.25) + assert observable is not None + is_numerator = is_numerator_observable(observable) + # Numerator: Z on the first copy's qubit, X on the ancilla. + # Denominator: only X on the ancilla. (str prints highest index first.) + terms = [str(term) for term, _coefficient in observable.terms] + assert terms == (["+XIZ"] if is_numerator else ["+XII"]) + calls.append((run_circuit.width, shots, is_numerator)) + if is_numerator: + return (1.5, 0.25) + return (2.0, 1.0) assert vd.run_numerator_circuit(hamiltonian, 3, estimator) == (1.5, 0.25) assert vd.run_denominator_circuit(2, estimator) == (2.0, 1.0) @@ -146,10 +166,10 @@ def estimator( assert mitigated[0] == pytest.approx(0.75) assert mitigated[1] == pytest.approx(0.203125) assert calls == [ - (2, 3, False), - (2, 2, True), - (2, 3, False), - (2, 2, True), + (3, 3, True), + (3, 2, False), + (3, 3, True), + (3, 2, False), ] @@ -208,8 +228,9 @@ def estimator( observable: Hamiltonian | None, shots: int | None, ) -> tuple[float, float]: - assert run_circuit.width == 2 - if observable is None: + assert run_circuit.width == 3 + assert observable is not None + if not is_numerator_observable(observable): assert shots == 2 return (2.0, 1.0) assert shots == 3 diff --git a/crates/binding-python/tests/gates/test_circuit_gate.py b/crates/binding-python/tests/gates/test_circuit_gate.py index a18d8416..969ef952 100644 --- a/crates/binding-python/tests/gates/test_circuit_gate.py +++ b/crates/binding-python/tests/gates/test_circuit_gate.py @@ -20,12 +20,202 @@ - Parametric CircuitGate creation and usage """ +from itertools import permutations + +import numpy as np import pytest from cqlib.circuit import Circuit, Parameter from cqlib.circuit.gates import CircuitGate +def _embed_operation_matrix(matrix, targets, width): + """Independent basis-index embedding: first gate argument is the MSB.""" + result = np.zeros((2**width, 2**width), dtype=complex) + for column in range(2**width): + local_column = 0 + for target in targets: + local_column = 2 * local_column + ((column >> target) & 1) + for local_row in range(2 ** len(targets)): + row = column + for position, target in enumerate(targets): + bit = (local_row >> (len(targets) - 1 - position)) & 1 + row = (row & ~(1 << target)) | (bit << target) + result[row, column] = matrix[local_row, local_column] + return result + + +class TestCircuitGateOperationMatrix: + @staticmethod + def assert_operations(circuit, expected): + # Cover snapshots returned by both collection and indexing APIs. + for operation in (circuit.operations[0], circuit[0]): + np.testing.assert_allclose(operation.matrix(), expected, rtol=0, atol=1e-12) + + @pytest.mark.parametrize("order", [[0, 1], [1, 0], [7, 2]]) + def test_positional_matrix(self, order): + body = Circuit(order) + body.x(order[0]) + circuit = Circuit(2) + circuit.append_circuit_gate(body.to_gate("first_x"), [0, 1]) + self.assert_operations(circuit, np.kron([[0, 1], [1, 0]], np.eye(2))) + + def test_bound_parameter_and_repeated_application(self): + body = Circuit([7]) + body.rx(7, Parameter("theta")) + gate = body.to_gate("rx") + for angle in (0.37, -0.61, 0.37): + circuit = Circuit(1) + circuit.append_circuit_gate(gate, [0], [angle]) + c, s = np.cos(angle / 2), -1j * np.sin(angle / 2) + self.assert_operations(circuit, np.array([[c, s], [s, c]])) + assert gate.used_symbols == ["theta"] + + @pytest.mark.parametrize("order", list(permutations([7, 2, 5]))) + @pytest.mark.parametrize("targets", [[3, 0, 2], [2, 3, 0]]) + def test_three_qubit_permutations_and_spectator(self, order, targets): + body = Circuit(list(order)) + body.h(order[0]) + body.rz(order[1], 0.29) + body.cx(order[0], order[2]) + body.set_global_phase(0.17) + expected = np.zeros((8, 8), dtype=complex) + for column in range(8): + first, middle, last = column >> 2, (column >> 1) & 1, column & 1 + for output_first in (0, 1): + row = (output_first << 2) | (middle << 1) | (last ^ output_first) + expected[row, column] = ( + (-1) ** (first * output_first) + / np.sqrt(2) + * np.exp(1j * (0.17 + (2 * middle - 1) * 0.29 / 2)) + ) + circuit = Circuit(4) + circuit.append_circuit_gate(body.to_gate("three"), targets) + self.assert_operations(circuit, expected) + full = _embed_operation_matrix(expected, targets, 4) + np.testing.assert_allclose(circuit.to_matrix(), full, rtol=0, atol=1e-12) + np.testing.assert_allclose( + circuit.to_symbolic_matrix().evaluate(), full, rtol=0, atol=1e-12 + ) + np.testing.assert_allclose( + circuit.decompose().to_matrix(), full, rtol=0, atol=1e-12 + ) + + @pytest.mark.parametrize("nested", [False, True]) + @pytest.mark.parametrize("inverse", [False, True]) + def test_signature_phase_and_inverse(self, nested, inverse): + theta, phi = Parameter("theta"), Parameter("phi") + body = Circuit([7, 2]) + body.rx(7, theta) + body.rz(2, phi) + body.cx(7, 2) + body.set_global_phase(theta + phi / 2) + gate = CircuitGate.with_signature( + "declared", body.to_gate("definition").circuit, ["unused", "phi", "theta"] + ) + arguments = [12.0, -0.21, 0.37] + if nested: + middle = Circuit([5, 1]) + middle.append_circuit_gate(gate, [5, 1], [0, phi, theta]) + gate = CircuitGate.with_signature( + "nested", middle.to_gate("middle").circuit, ["unused", "phi", "theta"] + ) + circuit = Circuit(2) + circuit.append_circuit_gate(gate, [1, 0], arguments) + if inverse: + circuit = circuit.inverse() + c, s = np.cos(0.37 / 2), -1j * np.sin(0.37 / 2) + rx = np.array([[c, s], [s, c]]) + rz = np.diag(np.exp(1j * np.array([0.21, -0.21]) / 2)) + cx = np.eye(4)[[0, 1, 3, 2]] + expected = np.exp(1j * (0.37 - 0.21 / 2)) * cx @ np.kron(rx, rz) + if inverse: + expected = expected.conj().T + self.assert_operations(circuit, expected) + np.testing.assert_allclose(circuit.to_matrix(), expected, rtol=0, atol=1e-12) + np.testing.assert_allclose( + circuit.to_symbolic_matrix().evaluate(), expected, rtol=0, atol=1e-12 + ) + + def test_zero_qubit_phase(self): + body = Circuit(0) + body.set_global_phase(Parameter("theta")) + circuit = Circuit(0) + circuit.append_circuit_gate(body.to_gate("phase"), [], [0.37]) + expected = np.array([[np.exp(0.37j)]]) + self.assert_operations(circuit, expected) + np.testing.assert_allclose(circuit.to_matrix(), expected, rtol=0, atol=1e-12) + + def test_unresolved_arguments_keep_existing_error_behavior(self): + body = Circuit(1) + body.rx(0, Parameter("theta")) + circuit = Circuit(1) + circuit.append_circuit_gate(body.to_gate("unresolved"), [0], [Parameter("x")]) + with pytest.raises(ValueError): + circuit.operations[0].matrix() + with pytest.raises(ValueError): + circuit[0].matrix() + + +class TestCircuitGateStorageOrder: + @pytest.mark.parametrize("order", [[7, 2], [1, 0], [2, 7], [0, 1]]) + @pytest.mark.parametrize("targets", [[0, 1], [1, 0]]) + def test_matrix_uses_internal_storage_order(self, order, targets): + inner = Circuit(order) + inner.x(order[0]) + outer = Circuit(2) + outer.append_circuit_gate(inner.to_gate("StoredOrderX"), targets) + expected = Circuit(2) + expected.x(targets[0]) + for output_order in (None, [1, 0]): + reference = expected.to_matrix(output_order) + np.testing.assert_allclose( + outer.to_matrix(output_order), reference, rtol=0, atol=1e-10 + ) + np.testing.assert_allclose( + outer.to_symbolic_matrix(output_order).evaluate(), + reference, + rtol=0, + atol=1e-10, + ) + np.testing.assert_allclose( + outer.decompose().to_matrix(output_order), reference, rtol=0, atol=1e-10 + ) + assert outer.to_matrix()[1 << targets[0], 0] == 1 + + @pytest.mark.parametrize("middle_order", [None, [0, 1], [5, 1]]) + @pytest.mark.parametrize("inverse", [False, True]) + def test_nested_parameterized_matrix_and_inverse(self, middle_order, inverse): + theta = Parameter("theta") + body = Circuit([7, 2]) + body.rx(7, theta) + body.cx(7, 2) + if middle_order is not None: + gate = body.to_gate("Inner") + body = Circuit(middle_order) + body.append_circuit_gate(gate, middle_order, [theta]) + outer = Circuit(2) + outer.append_circuit_gate(body.to_gate("Body"), [0, 1], [Parameter("x")]) + if inverse: + outer = outer.inverse() + symbolic = outer.to_symbolic_matrix() + for angle in (0.37, -0.61): + expected = Circuit(2) + expected.rx(0, angle) + expected.cx(0, 1) + if inverse: + expected = expected.inverse() + reference = expected.to_matrix() + bound = outer.assign_parameters({"x": angle}) + np.testing.assert_allclose(bound.to_matrix(), reference, rtol=0, atol=1e-10) + np.testing.assert_allclose( + symbolic.evaluate({"x": angle}), reference, rtol=0, atol=1e-10 + ) + np.testing.assert_allclose( + bound.decompose().to_matrix(), reference, rtol=0, atol=1e-10 + ) + + class TestCircuitGateCreation: """Test CircuitGate creation from circuits""" diff --git a/crates/binding-python/tests/gates/test_gphase.py b/crates/binding-python/tests/gates/test_gphase.py new file mode 100644 index 00000000..2e9e8df8 --- /dev/null +++ b/crates/binding-python/tests/gates/test_gphase.py @@ -0,0 +1,89 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Zero-qubit phase and controlled-phase matrix contracts.""" + +import numpy as np +import pytest + +from cqlib import Circuit, Parameter +from cqlib.circuit.gates import GPhase + + +@pytest.mark.parametrize("theta", [0.0, 0.37, -0.51, np.pi]) +@pytest.mark.parametrize("controls", [None, 0, 1, 2]) +def test_gphase_matrix_metadata_and_inverse(theta, controls): + base = GPhase(theta) + gate = base if controls is None else base.control(controls) + count = controls or 0 + assert gate.num_qubits == count + assert gate.num_ctrl_qubits == count + assert gate.num_params == 1 + expected = np.eye(1 << count, dtype=complex) + expected[-1, -1] = np.exp(1j * theta) + actual = gate.matrix() + assert actual.shape == expected.shape + np.testing.assert_allclose(actual, expected, rtol=0, atol=1e-12) + inverse = gate.inverse().matrix() + assert inverse.shape == expected.shape + np.testing.assert_allclose(inverse, expected.conj().T, rtol=0, atol=1e-12) + + +@pytest.mark.parametrize("num_qubits", [0, 1, 3]) +@pytest.mark.parametrize("symbolic", [False, True]) +def test_gphase_markers_accumulate_in_circuit_matrices(num_qubits, symbolic): + circuit = Circuit(num_qubits) + if num_qubits: + circuit.h(0) + baseline = circuit.to_matrix() + circuit.append_gate(GPhase(-0.21), []) + circuit.append_gate(GPhase(Parameter("theta") if symbolic else 0.37), []) + circuit.append_gate(GPhase(0.12), []) + circuit.set_global_phase(0.17) + expected = np.exp(1j * (-0.21 + 0.37 + 0.12 + 0.17)) * baseline + if not symbolic: + actual = circuit.to_matrix() + assert actual.shape == expected.shape + np.testing.assert_allclose(actual, expected, rtol=0, atol=1e-12) + expression = circuit.to_symbolic_matrix() + assert expression.shape == expected.shape + np.testing.assert_allclose( + expression.evaluate({"theta": 0.37}), expected, rtol=0, atol=1e-12 + ) + + +@pytest.mark.parametrize("controls", [[], [2], [2, 0]]) +@pytest.mark.parametrize("order", [[0, 1, 2], [2, 0, 1]]) +@pytest.mark.parametrize("symbolic", [False, True]) +def test_gphase_controlled_circuit_matrices(controls, order, symbolic): + circuit = Circuit(3) + circuit.h(1) + theta = Parameter("theta") if symbolic else 0.37 + circuit.append_mc_gate(GPhase(theta).control(len(controls)), controls) + spectator_bit = order.index(1) + mask = sum(1 << order.index(control) for control in controls) + expected = np.zeros((8, 8), dtype=complex) + for row in range(8): + for col in range(8): + if (row ^ col) & ~(1 << spectator_bit) == 0: + sign = -1 if row & col & (1 << spectator_bit) else 1 + phase = np.exp(0.37j) if row & mask == mask else 1 + expected[row, col] = phase * sign / np.sqrt(2) + if not symbolic: + actual = circuit.to_matrix(order) + assert actual.shape == (8, 8) + np.testing.assert_allclose(actual, expected, rtol=0, atol=1e-12) + expression = circuit.to_symbolic_matrix(order) + assert expression.shape == (8, 8) + np.testing.assert_allclose( + expression.evaluate({"theta": 0.37}), expected, rtol=0, atol=1e-12 + ) diff --git a/crates/binding-python/tests/gates/test_standard.py b/crates/binding-python/tests/gates/test_standard.py index 4c7770fe..a0d64e27 100644 --- a/crates/binding-python/tests/gates/test_standard.py +++ b/crates/binding-python/tests/gates/test_standard.py @@ -396,12 +396,12 @@ def test_phase_gate(self): assert np.allclose(mat, expected), "Phase gate matrix mismatch" def test_global_phase_gate(self): - """GPhase(θ) = e^(iθ) I (2x2)""" + """The zero-qubit GPhase matrix contains one scalar phase.""" theta = np.pi / 4 mat = GPhase(theta).matrix() - # GPhase is 1-qubit gate with 1 parameter, matrix is 2x2 - expected = np.exp(1j * theta) * np.eye(2) - assert np.allclose(mat, expected), "GPhase matrix mismatch" + expected = np.array([[np.exp(1j * theta)]]) + assert mat.shape == (1, 1) + np.testing.assert_allclose(mat, expected, rtol=0, atol=1e-12) def test_u_gate_general(self): """U gate is general single-qubit gate""" diff --git a/crates/binding-python/tests/ir/test_qasm3_gphase.py b/crates/binding-python/tests/ir/test_qasm3_gphase.py new file mode 100644 index 00000000..dca06a10 --- /dev/null +++ b/crates/binding-python/tests/ir/test_qasm3_gphase.py @@ -0,0 +1,85 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# Licensed under the Apache License, Version 2.0. See LICENSE.txt or +# http://www.apache.org/licenses/LICENSE-2.0. + +"""Global phase must survive serialization of reusable gate definitions.""" + +import numpy as np +import pytest + +from cqlib import Circuit, Parameter +from cqlib.circuit import UnitaryGate +from cqlib.circuit.gates import GPhase +from cqlib.ir import qasm3 +from cqlib.qis import Statevector + + +def assert_round_trip(circuit, expected, bindings=None): + output = qasm3.dumps(circuit) + loaded = qasm3.loads(output) + original = circuit.assign_parameters(bindings) if bindings else circuit + loaded = loaded.assign_parameters(bindings) if bindings else loaded + for candidate in [original, loaded]: + np.testing.assert_allclose(candidate.to_matrix(), expected, rtol=0, atol=1e-12) + np.testing.assert_allclose( + Statevector.from_circuit(candidate).data, + expected[:, 0], + rtol=0, + atol=1e-12, + ) + return output + + +@pytest.mark.parametrize("symbolic", [False, True]) +@pytest.mark.parametrize("explicit_phase", [False, True]) +@pytest.mark.parametrize("nested", [False, True]) +def test_nested_gate_global_phase_round_trip(symbolic, explicit_phase, nested): + theta = Parameter("theta") if symbolic else 0.37 + inner = Circuit([12]) + inner.h(12) + inner.set_global_phase(theta) + if explicit_phase: + inner.append_gate(GPhase(-0.21), []) + gate = inner.to_gate("fragment") + if nested: + middle = Circuit([5]) + middle.set_global_phase(0.11) + middle.append_circuit_gate(gate, [5], [theta] if symbolic else []) + gate = middle.to_gate("middle") + outer = Circuit(1) + outer.set_global_phase(-0.07) + outer.append_circuit_gate(gate, [0], [Parameter("outer_theta")] if symbolic else []) + phase = 0.37 - 0.07 + (0.11 if nested else 0) - (0.21 if explicit_phase else 0) + expected = np.exp(1j * phase) * np.array([[1, 1], [1, -1]]) / np.sqrt(2) + assert_round_trip(outer, expected, {"outer_theta": 0.37} if symbolic else None) + + +def test_phase_only_parameter_and_repeated_gate_calls(): + inner = Circuit(1) + inner.h(0) + inner.set_global_phase(Parameter("theta")) + gate = inner.to_gate("fragment") + outer = Circuit(1) + outer.append_circuit_gate(gate, [0], [0.37]) + outer.append_circuit_gate(gate, [0], [-0.51]) + output = assert_round_trip(outer, np.exp(-0.14j) * np.eye(2)) + assert output.count("gphase(theta);") == 1 + + +def test_unitary_gate_definition_global_phase_round_trip(): + inner = Circuit(1) + inner.h(0) + inner.set_global_phase(0.37) + inner.append_gate(GPhase(-0.21), []) + expected = np.exp(0.16j) * np.array([[1, 1], [1, -1]]) / np.sqrt(2) + gate = ( + UnitaryGate("phase_h", 1) + .with_matrix(expected) + .with_circuit(inner.to_gate("definition").circuit) + ) + outer = Circuit(1) + outer.append_unitary_gate(gate, [0]) + assert_round_trip(outer, expected) diff --git a/crates/binding-python/tests/parameter/test_arithmetic.py b/crates/binding-python/tests/parameter/test_arithmetic.py index 94b6a89a..3a769c9c 100644 --- a/crates/binding-python/tests/parameter/test_arithmetic.py +++ b/crates/binding-python/tests/parameter/test_arithmetic.py @@ -26,6 +26,28 @@ from cqlib.circuit import Parameter +def test_affine_coefficients_and_cancellation_residues(): + import math + + theta = Parameter("theta") + for coefficient in (1e-15, math.nextafter(1.0, 2.0)): + scaled = (theta * coefficient).simplify() + assert scaled.evaluate({"theta": 1.0}) == coefficient + assert scaled.replace("theta", Parameter(1.0)).evaluate() == coefficient + coefficient = math.nextafter(1.0, 2.0) + residue = (theta * coefficient - theta).simplify() + assert residue.evaluate({"theta": 1.0}) == coefficient - 1.0 + assert (Parameter(1e-15) - Parameter(0.0)).simplify().evaluate() == 1e-15 + + +def test_subnormal_parameter_division_preserves_representable_quotient(): + smallest = float.fromhex("0x0.0000000000001p-1022") + theta = Parameter("theta") + scaled = theta * smallest + assert scaled.simplify().evaluate({"theta": 1.0}) == smallest + assert (scaled / smallest).simplify().evaluate({"theta": 1.0}) == 1.0 + + class TestAddition: """Tests for addition operation.""" diff --git a/crates/binding-python/tests/parameter/test_substitution.py b/crates/binding-python/tests/parameter/test_substitution.py new file mode 100644 index 00000000..cb650b98 --- /dev/null +++ b/crates/binding-python/tests/parameter/test_substitution.py @@ -0,0 +1,107 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +import numpy as np +import pytest + +from cqlib import Circuit, Parameter + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_substitute_swaps_symbols_using_the_same_dictionary(reverse): + x, y = Parameter("x"), Parameter("y") + original = x + 2 * y + bindings = dict(reversed([("x", y), ("y", x)])) if reverse else {"x": y, "y": x} + + for _ in range(100): + result = original.substitute(bindings) + assert set(result.symbols) == {"x", "y"} + assert result.evaluate({"x": 1.0, "y": 3.0}) == 5.0 + + assert original.evaluate({"x": 1.0, "y": 3.0}) == 7.0 + assert bindings["x"] == y + assert bindings["y"] == x + + +@pytest.mark.parametrize( + "case", ["chain", "self", "cycle", "multiple_keys", "independent"] +) +def test_substitute_does_not_process_inserted_expressions(case): + x, y, z = (Parameter(name) for name in ("x", "y", "z")) + original, bindings, expected = { + "chain": (x, {"x": y + 1, "y": Parameter(2)}, 11.0), + "self": (x, {"x": x + 1}, 3.0), + "cycle": (x + 2 * y + 3 * z, {"x": y, "y": z, "z": x}, 56.0), + "multiple_keys": (x, {"x": y + z, "y": Parameter(1), "z": Parameter(2)}, 30.0), + "independent": (x + y, {"x": z + 1, "y": Parameter(2)}, 23.0), + }[case] + assert ( + original.substitute(bindings).evaluate({"x": 2.0, "y": 10.0, "z": 20.0}) + == expected + ) + + +@pytest.mark.parametrize("method", ["replace", "substitute"]) +@pytest.mark.parametrize("kind", ["polynomial", "function_polynomial", "nested"]) +def test_substitution_reaches_polynomials_and_nested_functions(method, kind): + x, y = Parameter("x"), Parameter("y") + base = x.sin() + original = { + "polynomial": x * x + x + 1, + "function_polynomial": base * base + 2 * base + 1, + "nested": ((x * x + x + 1) / (x + 2)).cos() + x ** (y + 1), + }[kind] + result = ( + original.replace("x", y) + if method == "replace" + else original.substitute({"x": y}) + ) + assert set(result.symbols) == {"y"} + assert result.evaluate({"y": 0.5}) == pytest.approx( + original.evaluate({"x": 0.5, "y": 0.5}), abs=1e-12 + ) + + +def test_substitute_preserves_unbound_symbols_constants_and_empty_bindings(): + x, y = Parameter("x"), Parameter("y") + original = x + y + for bindings in ({}, {"missing": Parameter(9)}): + result = original.substitute(bindings) + assert set(result.symbols) == {"x", "y"} + assert result.evaluate({"x": 2.0, "y": 3.0}) == 5.0 + partial = original.substitute({"x": Parameter(2)}) + assert partial.symbols == ["y"] + assert partial.evaluate({"y": 3.0}) == 5.0 + assert Parameter(0.25).substitute({"x": y}).evaluate() == 0.25 + + +@pytest.mark.parametrize( + "coefficient", [1e-16, np.nextafter(0.0, 1.0), 1.0 + np.finfo(float).eps] +) +def test_substitution_preserves_affine_coefficients(coefficient): + x, y = Parameter("x"), Parameter("y") + original = x * float(coefficient) + for result in (original.replace("x", y), original.substitute({"x": y})): + assert result.evaluate({"y": 1.0}) == coefficient + + +def test_numeric_circuit_assignment_remains_equivalent(): + x, y = Parameter("x"), Parameter("y") + circuit = Circuit(1) + circuit.rx(0, x + 2 * y) + expected = Circuit(1) + expected.rx(0, 7.0) + for bound in ( + circuit.assign_parameters({"x": 1.0, "y": 3.0}), + circuit.assign_parameters({"x": 1.0}).assign_parameters({"y": 3.0}), + ): + np.testing.assert_allclose(bound.to_matrix(), expected.to_matrix(), atol=1e-12) diff --git a/crates/binding-python/tests/qis/test_controlled_gphase.py b/crates/binding-python/tests/qis/test_controlled_gphase.py new file mode 100644 index 00000000..2b29f446 --- /dev/null +++ b/crates/binding-python/tests/qis/test_controlled_gphase.py @@ -0,0 +1,226 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# Licensed under the Apache License, Version 2.0. See LICENSE.txt or +# http://www.apache.org/licenses/LICENSE-2.0. + +"""Controlled zero-target phase evolution in the numerical simulators.""" + +import numpy as np +import pytest + +from cqlib import Circuit, Parameter +from cqlib.circuit import StandardGate +from cqlib.circuit.gates import GPhase +from cqlib.device import NoiseModel, SingleQubitNoise +from cqlib.qis import DensityMatrix, DensityMatrixNoise, Statevector + + +SIMULATORS = [Statevector, DensityMatrix, DensityMatrixNoise] + + +def assert_state(state, amplitudes): + if isinstance(state, Statevector): + actual, expected = state.data, amplitudes + else: + actual = state.state if isinstance(state, DensityMatrixNoise) else state.data + expected = np.outer(amplitudes, amplitudes.conj()) + np.testing.assert_allclose(actual, expected, rtol=0, atol=1e-12) + + +@pytest.mark.parametrize("simulator", SIMULATORS) +@pytest.mark.parametrize("num_qubits", [0, 1, 3]) +def test_controlled_gphase_preserves_uncontrolled_phase(simulator, num_qubits): + circuit = Circuit(num_qubits) + expected = np.zeros(1 << num_qubits, dtype=complex) + expected[0] = 1 + if num_qubits: + circuit.h(0) + expected[:2] = 1 / np.sqrt(2) + circuit.append_gate(GPhase(0.37), []) + circuit.set_global_phase(-0.21) + expected *= np.exp(0.16j) + assert_state(simulator.from_circuit(circuit), expected) + + +@pytest.mark.parametrize("simulator", SIMULATORS) +@pytest.mark.parametrize("theta", [0.0, 0.37, -0.51, np.pi]) +@pytest.mark.parametrize("initial", ["zero", "one", "plus"]) +@pytest.mark.parametrize("incremental", [False, True]) +def test_controlled_gphase_single_qubit(simulator, theta, initial, incremental): + circuit = Circuit(1) + expected = np.array([1, 0], dtype=complex) + if initial == "one": + circuit.x(0) + expected = np.array([0, 1], dtype=complex) + elif initial == "plus": + circuit.h(0) + expected = np.ones(2, dtype=complex) / np.sqrt(2) + if incremental: + state = simulator.from_circuit(circuit) + circuit = Circuit(1) + circuit.append_mc_gate(GPhase(theta).control(1), [0]) + expected[1] *= np.exp(1j * theta) + if incremental: + state.apply_circuit(circuit) + else: + state = simulator.from_circuit(circuit) + assert_state(state, expected) + + +@pytest.mark.parametrize("simulator", SIMULATORS) +@pytest.mark.parametrize("labels", [[0, 1, 2], [12, 5, 31]]) +@pytest.mark.parametrize("positions", [[2], [2, 0], [0, 2]]) +def test_controlled_gphase_labels_spectators_and_inverse(simulator, labels, positions): + circuit = Circuit(labels) + for qubit in labels: + circuit.h(qubit) + circuit.s(labels[1]) + controls = [labels[position] for position in positions] + phase = Circuit(labels) + gate = GPhase(0.37).control(len(controls)) + phase.append_mc_gate(gate, controls) + incremental = simulator.from_circuit(circuit) + incremental.apply_circuit(phase) + circuit.append_mc_gate(gate, controls) + direct = simulator.from_circuit(circuit) + indices = np.arange(8) + baseline = np.where(indices & 2, 1j, 1) / np.sqrt(8) + mask = sum(1 << position for position in positions) + expected = baseline * np.where(indices & mask == mask, np.exp(0.37j), 1) + assert_state(direct, expected) + assert_state(incremental, expected) + inverse = Circuit(labels) + inverse.append_mc_gate(gate.inverse(), controls) + incremental.apply_circuit(inverse) + assert_state(incremental, baseline) + + +@pytest.mark.parametrize("simulator", SIMULATORS) +def test_controlled_gphase_parameter_resolution(simulator): + circuit = Circuit(1) + circuit.h(0) + circuit.append_mc_gate(GPhase(Parameter("theta")).control(1), [0]) + with pytest.raises(ValueError, match="(?i)symbolic"): + simulator.from_circuit(circuit) + state = simulator(1) + with pytest.raises(ValueError, match="(?i)symbolic"): + state.apply_circuit(circuit) + bound = circuit.assign_parameters({"theta": -0.51}) + expected = np.array([1, np.exp(-0.51j)]) / np.sqrt(2) + assert_state(simulator.from_circuit(bound), expected) + + +@pytest.mark.parametrize("empty_model", [False, True]) +def test_controlled_gphase_noisy_simulator_without_errors(empty_model): + circuit = Circuit(1) + circuit.h(0) + circuit.append_mc_gate(GPhase(0.37).control(1), [0]) + model = NoiseModel() if empty_model else None + state = DensityMatrixNoise.from_circuit(circuit, model) + assert_state(state, np.array([1, np.exp(0.37j)]) / np.sqrt(2)) + + +@pytest.mark.parametrize("incremental", [False, True]) +def test_controlled_gphase_noise_follows_unitary_once_with_original_labels(incremental): + labels = [12, 5] + circuit = Circuit(labels) + circuit.x(12) + circuit.h(5) + model = NoiseModel() + probability = 0.23 + model.add_single_qubit_error( + StandardGate.GPhase, 5, SingleQubitNoise.bit_flip(probability) + ) + model.add_single_qubit_error( + StandardGate.GPhase, 12, SingleQubitNoise.bit_flip(1.0) + ) + if incremental: + state = DensityMatrixNoise.from_circuit(circuit, model) + circuit = Circuit(labels) + circuit.append_mc_gate(GPhase(0.37).control(1), [5]) + if incremental: + state.apply_circuit(circuit) + else: + state = DensityMatrixNoise.from_circuit(circuit, model) + amplitudes = np.array([0, 1, 0, np.exp(0.37j)]) / np.sqrt(2) + rho = np.outer(amplitudes, amplitudes.conj()) + flipped = np.arange(4) ^ 2 + expected = (1 - probability) * rho + probability * rho[np.ix_(flipped, flipped)] + np.testing.assert_allclose(state.state, expected, rtol=0, atol=1e-12) + + +@pytest.mark.parametrize("simulator", SIMULATORS) +@pytest.mark.parametrize("num_qubits", [0, 1, 3]) +@pytest.mark.parametrize("theta", [0.0, 0.37, -0.51, np.pi]) +@pytest.mark.parametrize("incremental", [False, True]) +def test_zero_control_gphase_evolution(simulator, num_qubits, theta, incremental): + preparation = Circuit(num_qubits) + expected = np.zeros(1 << num_qubits, dtype=complex) + expected[0] = 1 + if num_qubits: + preparation.h(0) + expected[:2] = 1 / np.sqrt(2) + circuit = Circuit(num_qubits) if incremental else preparation + circuit.append_mc_gate(GPhase(theta).control(0), []) + circuit.append_mc_gate(GPhase(-0.21).control(0), []) + circuit.set_global_phase(0.11) + expected *= np.exp(1j * (theta - 0.10)) + if incremental: + state = simulator.from_circuit(preparation) + state.apply_circuit(circuit) + else: + state = simulator.from_circuit(circuit) + assert_state(state, expected) + inverse = Circuit(num_qubits) + inverse.append_mc_gate(GPhase(theta - 0.10).control(0).inverse(), []) + state.apply_circuit(inverse) + assert_state(state, expected * np.exp(-1j * (theta - 0.10))) + + +@pytest.mark.parametrize("simulator", SIMULATORS) +def test_zero_control_gphase_parameter_resolution(simulator): + circuit = Circuit([12, 5]) + circuit.h(5) + circuit.append_mc_gate(GPhase(Parameter("theta")).control(0), []) + with pytest.raises(ValueError, match="(?i)symbolic"): + simulator.from_circuit(circuit) + with pytest.raises(ValueError, match="(?i)symbolic"): + simulator(2).apply_circuit(circuit) + bound = circuit.assign_parameters({"theta": -0.51}) + expected = np.array([1, 0, 1, 0], dtype=complex) * np.exp(-0.51j) / np.sqrt(2) + assert_state(simulator.from_circuit(bound), expected) + + +@pytest.mark.parametrize("empty_model", [False, True]) +@pytest.mark.parametrize("incremental", [False, True]) +def test_zero_control_gphase_noise_matches_plain_gate(empty_model, incremental): + model = NoiseModel() + if not empty_model: + model.add_single_qubit_error( + StandardGate.GPhase, 12, SingleQubitNoise.bit_flip(1.0) + ) + model.add_single_qubit_error( + StandardGate.H, 5, SingleQubitNoise.depolarizing(0.23) + ) + preparation = Circuit([12, 5]) + preparation.x(12) + preparation.h(5) + results = [] + for wrapped in [False, True]: + circuit = Circuit([12, 5]) + if not incremental: + circuit.x(12) + circuit.h(5) + if wrapped: + circuit.append_mc_gate(GPhase(0.37).control(0), []) + else: + circuit.append_gate(GPhase(0.37), []) + if incremental: + state = DensityMatrixNoise.from_circuit(preparation, model) + state.apply_circuit(circuit) + else: + state = DensityMatrixNoise.from_circuit(circuit, model) + results.append(state.state) + np.testing.assert_allclose(results[0], results[1], rtol=0, atol=1e-12) diff --git a/crates/binding-python/tests/qis/test_density_matrix_noise.py b/crates/binding-python/tests/qis/test_density_matrix_noise.py index 22184776..21687db0 100644 --- a/crates/binding-python/tests/qis/test_density_matrix_noise.py +++ b/crates/binding-python/tests/qis/test_density_matrix_noise.py @@ -101,6 +101,35 @@ def test_probabilities_with_readout(self): assert len(probs) == 4 assert abs(sum(probs) - 1.0) < 1e-10 + @pytest.mark.parametrize("ids", [[0, 1], [1, 0], [2, 0], [9, 2]]) + @pytest.mark.parametrize("bind_with_apply", [False, True]) + def test_readout_uses_circuit_ids_at_storage_positions(self, ids, bind_with_apply): + circuit = Circuit(ids) + receipt = circuit.measure(ids[0]) + model = NoiseModel() + model.add_readout_error(ids[0], ReadoutError(0.0, 1.0)) + if bind_with_apply: + sim = DensityMatrixNoise(2, model) + sim.apply_circuit(circuit) + else: + sim = DensityMatrixNoise.from_circuit(circuit, model) + + assert sim.probabilities_with_readout([0]) == [0.0, 1.0, 0.0, 0.0] + assert sim.probabilities_with_readout([1]) == [1.0, 0.0, 0.0, 0.0] + assert sim.probabilities_with_readout([1, 0]) == [0.0, 1.0, 0.0, 0.0] + assert sim.probabilities_with_readout([]) == sim.probabilities() + assert sim.probabilities() == [1.0, 0.0, 0.0, 0.0] + marginal = { + o.to_bitstring(1): p for o, p in sim.probs_with_readout(receipt).items() + } + assert marginal == {"1": 1.0} + + @pytest.mark.parametrize("model", [None, NoiseModel()]) + def test_readout_rejects_out_of_range_positions_without_errors(self, model): + sim = DensityMatrixNoise.from_circuit(Circuit([9, 2]), model) + with pytest.raises(IndexError): + sim.probabilities_with_readout([9]) + class TestDensityMatrixNoiseSingleQubitGates: """Test single-qubit gate operations with noise.""" diff --git a/crates/binding-python/tests/qis/test_density_matrix_targets.py b/crates/binding-python/tests/qis/test_density_matrix_targets.py new file mode 100644 index 00000000..061f03fc --- /dev/null +++ b/crates/binding-python/tests/qis/test_density_matrix_targets.py @@ -0,0 +1,141 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# Licensed under the Apache License, Version 2.0. See LICENSE.txt or +# http://www.apache.org/licenses/LICENSE-2.0. + +"""Target validation must precede any density matrix mutation.""" + +import numpy as np +import pytest + +from cqlib.qis import DensityMatrix, DensityMatrixNoise + + +def initial_state(): + amplitudes = np.arange(1, 9) + 1j * np.arange(8, 0, -1) + return amplitudes / np.linalg.norm(amplitudes) + + +def householder(dim): + vector = np.arange(1, dim + 1, dtype=float) + return (np.eye(dim) - 2 * np.outer(vector, vector) / (vector @ vector)).astype( + complex + ) + + +def state_data(state): + return state.state if isinstance(state, DensityMatrixNoise) else state.data + + +@pytest.mark.parametrize("simulator", [DensityMatrix, DensityMatrixNoise]) +@pytest.mark.parametrize("target", [0, 1, 2]) +@pytest.mark.parametrize( + "method,params", + [ + ("apply_cx", []), + ("apply_cz", []), + ("apply_cy", []), + ("apply_swap", []), + ("apply_rxx", [0.37]), + ("apply_ryy", [0.37]), + ("apply_rzz", [0.37]), + ("apply_rzx", [0.37]), + ("apply_crx", [0.37]), + ("apply_cry", [0.37]), + ("apply_crz", [0.37]), + ("apply_fsim", [0.37, -0.21]), + ], +) +def test_duplicate_two_qubit_targets(simulator, target, method, params): + state = simulator(3) + state.apply_h(0) + state.apply_s(0) + before = state_data(state).copy() + with pytest.raises(ValueError, match=rf"(?i)duplicate qubit index {target}\b"): + getattr(state, method)(target, target, *params) + np.testing.assert_array_equal(state_data(state), before) + + +@pytest.mark.parametrize("simulator", [DensityMatrix, DensityMatrixNoise]) +@pytest.mark.parametrize("targets", [(0, 0, 2), (0, 2, 0), (2, 0, 0)]) +def test_duplicate_ccx_targets(simulator, targets): + state = simulator(3) + state.apply_h(0) + before = state_data(state).copy() + with pytest.raises(ValueError, match=r"(?i)duplicate qubit index 0\b"): + state.apply_ccx(*targets) + np.testing.assert_array_equal(state_data(state), before) + + +@pytest.mark.parametrize("target", [0, 1, 2]) +def test_duplicate_custom_gate_targets(target): + state = DensityMatrix.from_state(3, initial_state()) + before = state.data.copy() + with pytest.raises(ValueError, match=rf"(?i)duplicate qubit index {target}\b"): + state.apply_double_qubits_gate(target, target, householder(4)) + np.testing.assert_array_equal(state.data, before) + + +@pytest.mark.parametrize( + "targets,duplicate", + [ + ([0, 0], 0), + ([1, 1], 1), + ([2, 2], 2), + ([0, 2, 0], 0), + ([0, 0, 2], 0), + ([2, 0, 0], 0), + ], +) +def test_duplicate_kraus_targets(targets, duplicate): + state = DensityMatrix.from_state(3, initial_state()) + before = state.data.copy() + with pytest.raises(ValueError, match=rf"(?i)duplicate qubit index {duplicate}\b"): + state.apply_kraus(targets, [householder(1 << len(targets)).ravel()]) + np.testing.assert_array_equal(state.data, before) + + +def embed_operator(operator, targets, num_qubits): + """Build the full operator independently, preserving target argument order.""" + dim = 1 << num_qubits + result = np.zeros((dim, dim), dtype=complex) + mask = sum(1 << target for target in targets) + for column in range(dim): + local_column = 0 + for target in targets: + local_column = (local_column << 1) | ((column >> target) & 1) + for local_row in range(1 << len(targets)): + row = column & ~mask + for offset, target in enumerate(reversed(targets)): + row |= ((local_row >> offset) & 1) << target + result[row, column] = operator[local_row, local_column] + return result + + +@pytest.mark.parametrize("targets", [[0, 1], [1, 0], [0, 2], [2, 0]]) +@pytest.mark.parametrize("method", ["custom", "kraus", "unitary", "mixed_channel"]) +def test_distinct_targets_preserve_matrix_order(targets, method): + amplitudes = initial_state() + state = DensityMatrix.from_state(3, amplitudes) + operator = householder(4) + full_operator = embed_operator(operator, targets, 3) + evolved = full_operator @ amplitudes + expected = np.outer(evolved, evolved.conj()) + if method == "custom": + state.apply_double_qubits_gate(*targets, operator) + elif method == "unitary": + state.apply_unitary_gate(targets, operator) + elif method == "kraus": + state.apply_kraus(targets, [operator.ravel()]) + else: + state.apply_kraus( + targets, + [ + np.sqrt(0.7) * operator.ravel(), + np.sqrt(0.3) * np.eye(4, dtype=complex).ravel(), + ], + ) + expected = 0.7 * expected + 0.3 * np.outer(amplitudes, amplitudes.conj()) + np.testing.assert_allclose(state.data, expected, rtol=0, atol=1e-12) diff --git a/crates/binding-python/tests/qis/test_fermion.py b/crates/binding-python/tests/qis/test_fermion.py new file mode 100644 index 00000000..125f38fd --- /dev/null +++ b/crates/binding-python/tests/qis/test_fermion.py @@ -0,0 +1,378 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Fermionic Python contracts and independent Fock-space comparisons.""" + +import copy +import itertools + +import numpy as np +import pytest + +from cqlib.qis import ( + FermionicLadder as Ladder, + FermionicOp as Op, + FermionToQubitMapper, + Hamiltonian, + JordanWignerMapper, + OccupationStateMapper, + Statevector, +) +from cqlib.circuit.ansatz import BasisEncoding, EvolutionStrategy, PauliEvolutionAnsatz + + +def fock_ladder(num_modes, mode, create): + """Independent ladder action on little-endian occupation basis states.""" + matrix = np.zeros((1 << num_modes, 1 << num_modes), dtype=complex) + for column in range(1 << num_modes): + occupied = bool(column & (1 << mode)) + if occupied == create: + continue + lower = column & ((1 << mode) - 1) + sign = (-1) ** bin(lower).count("1") + matrix[column ^ (1 << mode), column] = sign + return matrix + + +def fock_matrix(op): + dim = 1 << op.num_modes + result = np.zeros((dim, dim), dtype=complex) + for term, coefficient in op.terms: + matrix = np.eye(dim, dtype=complex) + for ladder in term: + matrix = matrix @ fock_ladder( + op.num_modes, ladder.mode, ladder.kind == "create" + ) + result += coefficient * matrix + return result + + +def test_exports_and_ladder_contract(): + from cqlib.qis.fermion import FermionicOp + + assert FermionicOp is Op + assert Op.__module__ == "cqlib.qis.fermion" + create = Ladder.create(2) + assert create.mode == 2 and create.kind == "create" + assert create.adjoint() == Ladder.annihilate(2) + assert create.adjoint().adjoint() == create + assert len({create, Ladder.create(2)}) == 1 + assert create != 2 + assert repr(create) == "FermionicLadder.create(2)" + with pytest.raises(AttributeError): + create.mode = 1 + with pytest.raises(TypeError): + Ladder() + + +def test_construction_snapshots_and_exact_zero(): + create = Ladder.create(1) + op = Op.from_terms(3, iter([([create], 2), ((create,), -1), ((), 1j)])) + assert op.num_modes == 3 and op.num_terms == 2 + assert all(isinstance(c, complex) for _, c in op.terms) + snapshot = op.terms + assert all(isinstance(term, tuple) for term, _ in snapshot) + snapshot.clear() + assert op.num_terms == 2 + assert Op.from_terms(3, []).is_zero() + assert Op.from_term(3, []).equiv(Op.identity(3)) + tiny = Op.from_term(3, [create], 1e-15) + assert not tiny.is_zero() + assert not tiny.equiv(Op(3)) + assert tiny.chop(atol=1e-15) is None + assert tiny.is_zero() + with pytest.raises(AttributeError): + op.num_modes = 1 + with pytest.raises(TypeError): + hash(op) + + +def test_arithmetic_adjoint_and_normal_order(): + a = Op.annihilation(2, 0) + b = Op.annihilation(2, 1) + identity = Op.identity(2) + assert (a * a.adjoint() + a.adjoint() * a).equiv(identity) + assert (a * b + b * a).equiv(Op(2)) + assert (a * b.adjoint() + b.adjoint() * a).equiv(Op(2)) + contraction = a * a.adjoint() + assert contraction != contraction.normal_order() + assert contraction.equiv(identity - Op.number(2, 0)) + assert not (a * a).is_zero() # Raw product is stored until normal ordering. + assert (a * a).normal_order().is_zero() + assert (a * b).adjoint() == b.adjoint() * a.adjoint() + assert (2j * a) == a * 2j == a.scaled(2j) + assert -a == a * -1 + assert sum([a, b], start=Op(2)) == a + b + assert Op.total_number(2).is_hermitian() + alias = a + a += b + assert alias == Op.annihilation(2, 0) + assert a == alias + b + + +def test_copy_and_mutation_failure_atomicity(): + op = Op.number(2, 0) + for duplicate in (op.copy(), copy.copy(op), copy.deepcopy(op)): + assert duplicate == op and duplicate is not op + duplicate.add_term([], 2) + assert duplicate != op + before = op.copy() + for term, coefficient, error in ( + ([Ladder.create(2)], 0, IndexError), + (["bad"], 1, TypeError), + ([], complex(float("nan"), 0), ValueError), + ): + with pytest.raises(error): + op.add_term(term, coefficient) + assert op == before + assert "num_modes=2" in repr(op) + assert "a†_0 a_0" in str(op) + assert str(Op(0)) == "0" and "I" in str(Op.identity(0)) + + +@pytest.mark.parametrize("value", [-1, 2**100]) +def test_index_errors(value): + error = IndexError if value < 0 else OverflowError + with pytest.raises(error): + Ladder.create(value) + with pytest.raises(error): + Op.creation(2, value) + with pytest.raises(ValueError if value < 0 else OverflowError): + Op(value) + with pytest.raises(ValueError if value < 0 else OverflowError): + JordanWignerMapper().num_qubits(value) + + +@pytest.mark.parametrize("value", [1.2, "1", None]) +def test_type_errors(value): + with pytest.raises(TypeError): + Ladder.create(value) + with pytest.raises(TypeError): + Op(value) + if not isinstance(value, float): + with pytest.raises(TypeError): + Op.from_term(2, [], value) + + +@pytest.mark.parametrize("atol", [-1, float("nan"), float("inf")]) +def test_invalid_tolerances(atol): + op = Op.number(2, 0) + before = op.copy() + for operation in ( + lambda: op.chop(atol=atol), + lambda: op.equiv(before, atol=atol), + lambda: op.is_hermitian(atol=atol), + ): + with pytest.raises(ValueError): + operation() + assert op == before + + +def test_arithmetic_errors_and_reflected_dispatch(): + a = Op.number(2, 0) + b = Op.number(3, 0) + for operation in (lambda: a + b, lambda: a - b, lambda: a * b, lambda: a.equiv(b)): + with pytest.raises(ValueError): + operation() + for operation in (lambda: a + 1, lambda: a * "x", lambda: "x" * a): + with pytest.raises(TypeError): + operation() + assert a.__add__(object()) is NotImplemented + assert a.__sub__(object()) is NotImplemented + assert a.__mul__(object()) is NotImplemented + assert a.__rmul__(object()) is NotImplemented + assert a.__eq__(object()) is NotImplemented + + class Reflected: + def __rmul__(self, other): + return "reflected" + + assert a * Reflected() == "reflected" + for value in (float("nan"), float("inf"), complex(0, float("inf"))): + with pytest.raises(ValueError): + Op(2) * value + with pytest.raises(ValueError): + Op.from_term(2, [], value) + large = Op.from_term(2, [], 1e308) + before = large.copy() + with pytest.raises(ValueError): + large.add_term([], 1e308) + assert large == before + + +@pytest.mark.parametrize( + "sources,targets", [([], []), ([0], [1, 2]), ([0, 0], [1, 2]), ([0], [0])] +) +def test_excitation_validation(sources, targets): + with pytest.raises(ValueError): + Op.excitation_generator(4, sources, targets) + + +def test_mapping_against_independent_fock_products(): + mapper = JordanWignerMapper() + ladders = [ + factory(p) for factory in (Ladder.create, Ladder.annihilate) for p in range(2) + ] + # Exhaustive ordered products exercise JW phases, contractions and fermionic signs. + for length in range(4): + for term in itertools.product(ladders, repeat=length): + op = Op.from_term(2, term, 0.3 + 0.2j) + expected = fock_matrix(op) + np.testing.assert_allclose( + mapper.map_operator(op).to_matrix(), expected, atol=1e-15 + ) + np.testing.assert_allclose( + fock_matrix(op.normal_order()), expected, atol=1e-15 + ) + a = Op.annihilation(2, 0) + np.testing.assert_allclose( + mapper.map_operator(a.adjoint()).to_matrix(), fock_matrix(a).conj().T + ) + combo = Op.from_terms( + 2, [((), 1j), ([Ladder.create(1)], 0.7), ([Ladder.create(1)], 0.3)] + ) + np.testing.assert_allclose( + mapper.map_operator(combo).to_matrix(), fock_matrix(combo) + ) + for op in (Op.number(2, 1), Op.total_number(2)): + np.testing.assert_allclose(mapper.map_operator(op).to_matrix(), fock_matrix(op)) + + +def test_zero_identity_and_occupations(): + mapper = JordanWignerMapper() + for n in (0, 1, 3): + zero = mapper.map_operator(Op(n)) + assert ( + isinstance(zero, Hamiltonian) + and zero.num_qubits == n + and zero.num_terms == 0 + ) + np.testing.assert_allclose(zero.to_matrix(), np.zeros((1 << n, 1 << n))) + np.testing.assert_allclose( + mapper.map_operator(Op.identity(n)).to_matrix(), np.eye(1 << n) + ) + assert mapper.map_occupation([]) == [] + assert mapper.map_occupation([1, False, True]) == [True, False, True] + for value in (-1, 2, 256, 2**100): + with pytest.raises(ValueError): + mapper.map_occupation([value]) + with pytest.raises(TypeError): + mapper.map_occupation([1.0]) + circuit = BasisEncoding(mapper.map_occupation([1, 0, 1])).build_circuit("hf") + state = Statevector.from_circuit(circuit) + np.testing.assert_allclose(state.data, np.eye(8)[5]) + + +def test_integer_protocol_validation(): + class ValidIndex: + def __index__(self): + return 1 + + class InvalidIndex: + def __index__(self): + return 1.0 + + class InstanceOnlyIndex: + def __init__(self): + self.__index__ = lambda: 1 + + mapper = JordanWignerMapper() + assert Ladder.create(ValidIndex()) == Ladder.create(1) + assert mapper.map_occupation([ValidIndex()]) == [True] + assert mapper.num_qubits(ValidIndex()) == 1 + assert Op(np.int64(2)).num_modes == 2 + assert mapper.map_occupation(np.array([0, 1], dtype=np.int64)) == [False, True] + for value in (InvalidIndex(), InstanceOnlyIndex()): + for operation in ( + lambda: Ladder.create(value), + lambda: Op(value), + lambda: mapper.num_qubits(value), + lambda: mapper.map_occupation([value]), + ): + with pytest.raises(TypeError): + operation() + + +def test_protocols_and_python_extension(): + mapper = JordanWignerMapper() + assert isinstance(mapper, FermionToQubitMapper) + assert isinstance(mapper, OccupationStateMapper) + + class CustomMapper: + def map_operator(self, op): + return mapper.map_operator(op) + + def num_qubits(self, num_modes): + return num_modes + + custom = CustomMapper() + assert isinstance(custom, FermionToQubitMapper) + assert not isinstance(custom, OccupationStateMapper) + np.testing.assert_allclose( + custom.map_operator(Op.number(2, 0)).to_matrix(), fock_matrix(Op.number(2, 0)) + ) + + +def test_mapping_preserves_representable_subnormal_and_near_unit_coefficients(): + smallest = float.fromhex("0x0.0000000000001p-1022") + mapper = JordanWignerMapper() + scalar = Op.from_term(0, [], smallest) + assert scalar.normal_order().terms[0][1].real == smallest + assert mapper.map_operator(scalar).terms[0][1].real == smallest + creation = Op.creation(1, 0).scaled(smallest * 2) + assert all( + abs(coefficient) == smallest + for _, coefficient in mapper.map_operator(creation).terms + ) + assert mapper.map_operator(creation).to_matrix()[1, 0].real == smallest * 2 + almost_one = float(np.nextafter(1.0, 2.0)) + number = Op.number(1, 0).scaled(almost_one) + assert number.terms[0][1].real == almost_one + assert mapper.map_operator(number).to_matrix()[1, 1].real == almost_one + + +def test_excitation_evolution_with_independent_parameters(): + mapper = JordanWignerMapper() + generators = [ + Op.excitation_generator(4, [0, 1], [2, 3]), + Op.excitation_generator(4, [0], [2]), + ] + assert generators[0].is_hermitian() + assert Op.excitation_generator(4, [1, 0], [2, 3]).equiv(-generators[0]) + circuit = BasisEncoding(mapper.map_occupation([1, 1, 0, 0])).build_circuit("hf") + for name, generator in zip(("theta_double", "theta_single"), generators): + block = ( + PauliEvolutionAnsatz(mapper.map_operator(generator)) + .with_strategy(EvolutionStrategy.exact()) + .with_time_param_name(name) + .build_circuit("ignored") + ) + circuit.compose(block) + assert set(circuit.symbols) == {"theta_double", "theta_single"} + angles = {"theta_double": 0.23, "theta_single": -0.37} + partial = circuit.assign_parameters({"theta_double": angles["theta_double"]}) + assert partial.symbols == ["theta_single"] + bound = partial.assign_parameters({"theta_single": angles["theta_single"]}) + actual = Statevector.from_circuit(bound) + expected = np.eye(16, dtype=complex)[3] + for generator, theta in zip(generators, angles.values()): + matrix = fock_matrix(generator) + eigenvalues, eigenvectors = np.linalg.eigh(matrix) + expected = ( + (eigenvectors * np.exp(-1j * theta * eigenvalues)) + @ eigenvectors.conj().T + @ expected + ) + np.testing.assert_allclose(actual.data, expected, atol=1e-14) + assert mapper.map_operator(Op.total_number(4)).expectation_statevector( + actual + ) == pytest.approx(2) diff --git a/crates/binding-python/tests/qis/test_hamiltonian.py b/crates/binding-python/tests/qis/test_hamiltonian.py index e9065722..e57894ea 100644 --- a/crates/binding-python/tests/qis/test_hamiltonian.py +++ b/crates/binding-python/tests/qis/test_hamiltonian.py @@ -12,10 +12,279 @@ import pytest import math +import warnings import numpy as np from cqlib.qis import Hamiltonian, PauliString, Phase, TrotterMode +@pytest.fixture(params=["from_list", "add_term", "scale"]) +def hamiltonian_with_coefficient(request): + def make(pauli, coefficient): + if request.param == "from_list": + return Hamiltonian.from_list([(pauli, coefficient)]) + if request.param == "add_term": + h = Hamiltonian(1) + assert h.add_term(pauli, coefficient) is None + else: + h = Hamiltonian.from_pauli(pauli) + assert h.scale(coefficient) is None + return h + + return make + + +@pytest.mark.parametrize("scalar_type", [complex, np.complex128, np.complex64]) +@pytest.mark.parametrize( + "label, coefficient", [("iX", -1j), ("X", 1.25 - 2.5j), ("X", 2 + 0j)] +) +def test_hamiltonian_complex_scalar_coefficients( + hamiltonian_with_coefficient, scalar_type, label, coefficient +): + # In particular, (-i) * (iX) must be X rather than the zero operator. + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + h = hamiltonian_with_coefficient( + PauliString.from_str(label), scalar_type(coefficient) + ) + assert h.terms[0][1] == coefficient + assert not caught + phase = 1j if label == "iX" else 1 + expected = np.array([[0, coefficient * phase], [coefficient * phase, 0]]) + np.testing.assert_array_equal(h.to_matrix(), expected) + + +@pytest.mark.parametrize( + "coefficient, expected", + [ + (2, 2), + (2.5, 2.5), + (np.int64(2), 2), + (np.float32(2.5), 2.5), + (np.float64(2.5), 2.5), + ((1.25, -2.5), 1.25 - 2.5j), + ((np.float32(1.25), np.float64(-2.5)), 1.25 - 2.5j), + ], +) +def test_hamiltonian_real_and_tuple_coefficients( + hamiltonian_with_coefficient, coefficient, expected +): + with warnings.catch_warnings(): + warnings.simplefilter("error") + h = hamiltonian_with_coefficient(PauliString.from_str("X"), coefficient) + assert h.terms[0][1] == expected + np.testing.assert_array_equal(h.to_matrix(), [[0, expected], [expected, 0]]) + + +@pytest.mark.parametrize("coefficient", ["1+2j", object(), (), (1,), (1, 2, 3)]) +def test_hamiltonian_rejects_invalid_coefficient( + hamiltonian_with_coefficient, coefficient +): + with pytest.raises(ValueError, match="Coefficient must be"): + hamiltonian_with_coefficient(PauliString.from_str("X"), coefficient) + + +class _BrokenComplexCoefficient: + def __complex__(self): + raise RuntimeError("complex conversion failed") + + def __float__(self): + return 0.0 # A failed complex conversion must not fall back to this. + + +def test_hamiltonian_propagates_complex_conversion_error(hamiltonian_with_coefficient): + with pytest.raises(RuntimeError, match="complex conversion failed"): + hamiltonian_with_coefficient( + PauliString.from_str("X"), _BrokenComplexCoefficient() + ) + + +@pytest.mark.parametrize("method", ["add_term", "scale"]) +@pytest.mark.parametrize( + "coefficient, error", + [ + (object(), ValueError), + (("invalid", 1), TypeError), + (_BrokenComplexCoefficient(), RuntimeError), + ], +) +def test_hamiltonian_coefficient_error_preserves_state(method, coefficient, error): + h = Hamiltonian.from_list([(PauliString.from_str("Z"), 2)]) + before = h.copy() + with pytest.raises(error): + if method == "add_term": + h.add_term(PauliString.from_str("X"), coefficient) + else: + h.scale(coefficient) + assert h == before + np.testing.assert_array_equal(h.to_matrix(), [[2, 0], [0, -2]]) + + +def test_checked_sparse_algebra_and_legacy_compatibility(): + x = Hamiltonian.from_terms(1, [(PauliString.from_str("X"), 1)]) + z = Hamiltonian.from_pauli(PauliString.from_str("Z")) + np.testing.assert_array_equal((x * z).to_matrix(), x.to_matrix() @ z.to_matrix()) + np.testing.assert_array_equal( + (x * z).adjoint().to_matrix(), (x.to_matrix() @ z.to_matrix()).conj().T + ) + assert (x - x).num_terms == 0 + assert (2j * x).equiv(x * 2j) + assert (-x).equiv(x.scaled(-1)) + assert x.add(x).equiv(x * 2) + assert x.add(x).num_terms == 1 + # Existing addition and mutation contracts remain compatible. + legacy = x + x + assert legacy.num_terms == 2 + legacy += x + assert legacy.num_terms == 3 + assert legacy.normalized().num_terms == 1 + assert legacy.add_term(PauliString.from_str("Z"), 1) is None + assert legacy.scale(2) is None + + +def test_checked_normalization_and_truncation(): + p = PauliString.from_str("X") + h = Hamiltonian.from_terms(1, [(p, 1e-15), (PauliString.from_str("+iX"), 2e-15)]) + assert h.num_terms == 1 + assert h.terms[0][1] == complex(1e-15, 2e-15) + assert h.normalized().terms == h.terms + assert not h.equiv(Hamiltonian(1)) + truncated = h.copy() + assert truncated.chop(atol=3e-15) is None + assert truncated.num_terms == 0 and truncated.num_qubits == 1 + legacy = h.copy() + legacy.simplify() + assert legacy.num_terms == 0 # Legacy behavior is deliberately retained. + assert Hamiltonian.from_terms(5, []).num_qubits == 5 + assert Hamiltonian.from_terms(0, []).to_matrix().shape == (1, 1) + + +def test_checked_tensor_and_qubit_embedding(): + x = Hamiltonian.from_pauli(PauliString.from_str("X")) + z = Hamiltonian.from_pauli(PauliString.from_str("Z")) + np.testing.assert_array_equal( + x.tensor(z).to_matrix(), np.kron(x.to_matrix(), z.to_matrix()) + ) + embedded = x.remap_qubits([2], target_width=3) + assert embedded.equiv(Hamiltonian.from_pauli(PauliString.from_str("XII"))) + assert x.tensor(Hamiltonian(2)).num_qubits == 3 + wide = x.remap_qubits([69], target_width=70) + assert wide.num_qubits == 70 and wide.num_terms == 1 + assert wide.equiv(wide.adjoint()) + for mapping, width in (([], 1), ([1], 1), ([0, 1], 2)): + with pytest.raises(ValueError): + x.remap_qubits(mapping, width) + with pytest.raises(ValueError): + x.tensor(z).remap_qubits([0, 0], 2) + with pytest.raises(IndexError): + x.remap_qubits([-1], 1) + with pytest.raises(TypeError): + x.remap_qubits([0.5], 1) + + +def test_checked_validation_and_failure_atomicity(): + x = Hamiltonian.from_pauli(PauliString.from_str("X")) + with pytest.raises(ValueError): + Hamiltonian.from_terms(2, [(PauliString.from_str("X"), 0)]) + with pytest.raises(ValueError): + Hamiltonian.from_terms(1, [(PauliString.from_str("X"), float("nan"))]) + with pytest.raises(TypeError): + Hamiltonian.from_terms(1, [(PauliString.from_str("X"), "invalid")]) + with pytest.raises(ValueError): + Hamiltonian.from_terms(-1, []) + for operation in ( + lambda: x.add(Hamiltonian(2)), + lambda: x - Hamiltonian(2), + lambda: x * Hamiltonian(2), + lambda: x.equiv(Hamiltonian(2)), + lambda: Hamiltonian(1).scaled(float("inf")), + ): + with pytest.raises(ValueError): + operation() + assert x.__mul__(object()) is NotImplemented + assert x.__sub__(object()) is NotImplemented + assert x.__rmul__(object()) is NotImplemented + assert x.__add__(object()) is NotImplemented + assert x.__eq__(object()) is NotImplemented + assert x != object() + for atol in (-1, float("nan"), float("inf")): + before = x.copy() + with pytest.raises(ValueError): + x.chop(atol=atol) + assert x == before + with pytest.raises(ValueError): + x.equiv(before, atol=atol) + with pytest.raises(ValueError): + x.is_hermitian(atol=atol) + overflow = x.scaled(1e308) + with pytest.raises(ValueError): + overflow.add(overflow) + with pytest.raises(ValueError): + overflow * 2 + invalid = x.copy() + invalid.scale(float("inf")) # Legacy scale retains its historical behavior. + before = invalid.copy() + with pytest.raises(ValueError): + invalid.chop() + assert invalid.num_qubits == before.num_qubits + assert invalid.num_terms == before.num_terms + for (_, actual), (_, expected) in zip(invalid.terms, before.terms): + assert actual.real == expected.real + assert math.isnan(actual.imag) and math.isnan(expected.imag) + + +def test_hermitian_projection_preserves_small_real_coefficients(): + h = Hamiltonian.from_terms(1, [(PauliString.from_str("X"), 1e-15 + 1e-11j)]) + assert not h.is_hermitian() + assert h.is_hermitian(atol=2e-11) + projected = h.normalized_hermitian() + assert projected.terms[0][1] == complex(1e-15) + assert h.terms[0][1].imag == 1e-11 # Projection returns a copy. + purely_imaginary = Hamiltonian.from_terms(1, [(PauliString.from_str("X"), 1e-11j)]) + assert purely_imaginary.normalized_hermitian().num_terms == 0 + with pytest.raises(ValueError): + Hamiltonian.from_terms( + 1, [(PauliString.from_str("X"), 2e-10j)] + ).normalized_hermitian() + + +def test_sparse_subnormal_and_near_unit_coefficients(): + smallest = float.fromhex("0x0.0000000000001p-1022") + scalar = Hamiltonian.from_terms(0, [(PauliString(0), smallest)]) + assert scalar.normalized().terms[0][1].real == smallest + assert scalar.scaled(2).terms[0][1].real == smallest * 2 + assert scalar.to_matrix()[0, 0].real == smallest + almost_one = float(np.nextafter(1.0, 2.0)) + x = Hamiltonian.from_pauli(PauliString.from_str("X")) + scaled = almost_one * x + assert scaled.terms[0][1].real == almost_one + assert scaled.adjoint().terms[0][1].real == almost_one + residue = scaled - x + assert residue.terms[0][1].real == almost_one - 1.0 + + +def test_small_symbolic_evolution_preserves_rotation_and_global_phase(): + from cqlib.circuit.ansatz import EvolutionStrategy, PauliEvolutionAnsatz + from cqlib.qis import Statevector + + small = 1e-12 + for label in ("X", "I"): + h = Hamiltonian.from_terms(1, [(PauliString.from_str(label), small)]) + circuit = ( + PauliEvolutionAnsatz(h) + .with_strategy(EvolutionStrategy.exact()) + .with_time_param_name("theta") + .build_circuit("small") + ) + with pytest.raises(ValueError): + Statevector.from_circuit( + circuit + ) # Identity-only symbolic phase must also be bound. + bound = circuit.assign_parameters({"theta": 1.0}) + state = Statevector.from_circuit(bound).data + index = 1 if label == "X" else 0 + assert state[index].imag == pytest.approx(-math.sin(small), rel=1e-14, abs=0) + + def test_hamiltonian_initialization(): h = Hamiltonian(2) assert h.num_qubits == 2 @@ -721,3 +990,32 @@ def test_hamiltonian_from_list_rejects_mixed_qubit_counts(): (PauliString.from_str("ZZ"), 1.0), ] ) + + +@pytest.mark.parametrize("deep", [False, True]) +@pytest.mark.parametrize("empty", [False, True]) +def test_python_copy_protocols(deep, empty): + from copy import copy, deepcopy + + original = Hamiltonian(2) + if not empty: + original.add_term(PauliString.from_str("ZZ"), 0.5 + 0.25j) + duplicate = (deepcopy if deep else copy)(original) + assert duplicate is not original + assert duplicate == original + assert duplicate.num_qubits == 2 + duplicate.add_term(PauliString.from_str("XX"), 0.3) + assert duplicate.num_terms == original.num_terms + 1 + + +def test_nested_deepcopy_preserves_aliases_without_sharing_source(): + from copy import deepcopy + + original = Hamiltonian(1) + original.add_term(PauliString.from_str("Z"), 1.0) + snapshot = deepcopy({"first": original, "nested": [original]}) + assert snapshot["first"] is snapshot["nested"][0] + assert snapshot["first"] is not original + snapshot["first"].scale(2.0) + assert original.terms[0][1] == 1.0 + assert snapshot["first"].terms[0][1] == 2.0 diff --git a/crates/binding-python/tests/qis/test_p1_regressions.py b/crates/binding-python/tests/qis/test_p1_regressions.py new file mode 100644 index 00000000..f8e1f2dd --- /dev/null +++ b/crates/binding-python/tests/qis/test_p1_regressions.py @@ -0,0 +1,126 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Public API regressions for P1 numerical and simulation bugs.""" + +import struct + +import numpy as np +import pytest +from cqlib.circuit import Circuit, Qubit, StandardGate +from cqlib.device import NoiseModel, SingleQubitNoise +from cqlib.qis import ( + Statevector, + DensityMatrix, + DensityMatrixNoise, + Hamiltonian, + PauliString, + TrotterMode, + entropy, +) + + +@pytest.mark.parametrize( + "constructor", + [Statevector, DensityMatrix, DensityMatrixNoise, DensityMatrix.maximally_mixed], +) +def test_invalid_dimensions_raise_value_error(constructor): + bits = struct.calcsize("P") * 8 + for n in [bits - 4, bits, 2**bits - 1]: + with pytest.raises(ValueError, match="dimension"): + constructor(n) + for n in [0, 1, 2]: + assert np.sum(constructor(n).probabilities()) == pytest.approx(1.0) + + +def test_pauli_probability_boundary(): + noise = SingleQubitNoise.pauli(0.3, 0.6, 0.1) + assert noise.is_valid() + assert all(np.isfinite(k).all() for k in noise.to_kraus()) + model = NoiseModel() + model.add_single_qubit_error(StandardGate.X, 0, noise) + sim = DensityMatrixNoise(1, model) + sim.apply_x(0) + np.testing.assert_allclose(sim.probabilities(), [0.9, 0.1], atol=1e-12) + + +def test_gate_noise_uses_sparse_labels(): + model = NoiseModel() + model.add_single_qubit_error(StandardGate.X, 5, SingleQubitNoise.bit_flip(1.0)) + circuit = Circuit([Qubit(5)]) + circuit.x(Qubit(5)) + sim = DensityMatrixNoise.from_circuit(circuit, model) + np.testing.assert_allclose(sim.probabilities(), [1.0, 0.0], atol=1e-12) + sim.apply_x(0) + np.testing.assert_allclose(sim.probabilities(), [1.0, 0.0], atol=1e-12) + + +def test_formation_entropy_of_rotated_maximally_entangled_state(): + state = np.array( + [ + -0.5917562523120286 - 0.14345273890626087j, + 0.12739228627789673 + 0.3361800930257551j, + -0.06600502193827436 + 0.35339664207352467j, + -0.5571108451004554 + 0.2457267928442915j, + ] + ) + result = entropy.entanglement_of_formation(DensityMatrix.from_state(2, state)) + assert np.isfinite(result) and 0 <= result <= 1 + # Square roots amplify null-space eigenvalue noise to O(sqrt(machine epsilon)). + tolerance = 8 * np.sqrt(np.finfo(float).eps) + assert result == pytest.approx(1.0, rel=0, abs=tolerance) + + +def test_renyi_extreme_orders(): + dm = DensityMatrix.maximally_mixed(1) + for alpha in [1.0 - 1e-12, 1.0 + 1e-12, 2000.0, float("inf")]: + assert entropy.renyi_entropy(dm, alpha) == pytest.approx(1.0, abs=1e-10) + with pytest.raises(ValueError): + entropy.renyi_entropy(dm, float("nan")) + small = DensityMatrix.from_density_matrix( + 1, np.diag([1 - 1e-14, 1e-14]).astype(complex).flatten() + ) + assert entropy.renyi_entropy(small, 0.1) == pytest.approx( + 0.06257881098503021, abs=1e-12 + ) + + +@pytest.mark.parametrize("method", ["to_trotter_circuit", "to_evolution_circuit"]) +def test_evolution_retains_small_terms(method): + h = Hamiltonian(1) + h.add_term(PauliString.from_str("Z"), 1e-11) + circuit = getattr(h, method)(1e11, 3, TrotterMode.first_order()) + # Probabilities alone cannot expose this regression: compare the full matrix. + from cqlib.circuit import circuit_to_matrix + + np.testing.assert_allclose( + circuit_to_matrix(circuit), np.diag(np.exp([-1j, 1j])), atol=1e-12 + ) + + +@pytest.mark.parametrize("state_type", [Statevector, DensityMatrix, DensityMatrixNoise]) +def test_oversized_circuit_raises_value_error(state_type): + with pytest.raises(ValueError, match="dimension"): + state_type.from_circuit(Circuit(struct.calcsize("P") * 8)) + + +@pytest.mark.parametrize( + "constructor", + [ + Statevector.from_state, + DensityMatrix.from_state, + DensityMatrix.from_density_matrix, + ], +) +def test_oversized_array_constructors_raise_value_error(constructor): + with pytest.raises(ValueError, match="dimension"): + constructor(struct.calcsize("P") * 8, []) diff --git a/crates/binding-python/tests/qis/test_p2_regressions.py b/crates/binding-python/tests/qis/test_p2_regressions.py new file mode 100644 index 00000000..b809b5e8 --- /dev/null +++ b/crates/binding-python/tests/qis/test_p2_regressions.py @@ -0,0 +1,240 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +import itertools +import numpy as np +import pytest +from cqlib.circuit import ( + Circuit, + Qubit, + StandardGate, + Instruction, + Parameter, + circuit_to_matrix, +) +from cqlib.device import NoiseModel, SingleQubitNoise +from cqlib.qis import ( + Statevector, + DensityMatrix, + DensityMatrixNoise, + Hamiltonian, + PauliString, + entropy, +) +from cqlib.error_mitigation.zne import ZNEMitigation + + +@pytest.mark.parametrize( + "constructor", [Statevector.from_state, DensityMatrix.from_state] +) +@pytest.mark.parametrize( + "bad", [float("nan"), float("inf"), -float("inf"), np.finfo(float).max] +) +def test_nonfinite_norm_rejected(constructor, bad): + for amp in [complex(bad, 0), complex(0, bad)]: + with pytest.raises(ValueError, match="normalized"): + constructor(1, [amp, 0j]) + assert constructor(0, [1j]).probabilities() == pytest.approx([1]) + assert constructor(1, [0.6, 0.8j]).probabilities() == pytest.approx([0.36, 0.64]) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), -float("inf")]) +def test_nonfinite_density_matrix_rejected(bad): + for pos in range(4): + for value in [complex(bad, 0), complex(0, bad)]: + data = np.eye(2, dtype=complex).flatten() / 2 + data[pos] = value + with pytest.raises(ValueError): + DensityMatrix.from_density_matrix(1, data) + + +@pytest.mark.parametrize("label", ["iZ", "-iI", "iX"]) +def test_real_expectations_reject_nonhermitian(label): + p = PauliString.from_str(label) + h = Hamiltonian(1) + h.add_term(p, 1) + measurements = [(p, {"0": 1.0})] + for observable in [p, h]: + for state in [Statevector(1), DensityMatrix(1), DensityMatrixNoise(1)]: + with pytest.raises(ValueError, match="Hermitian"): + state.expectation(observable) + with pytest.raises(ValueError, match="Hermitian"): + observable.expectation_probs(measurements) + with pytest.raises(ValueError, match="Hermitian"): + p.expectation({"0": 1.0}) + + +def test_merged_hermitian_and_small_coefficients(): + for terms, expected in [ + ([("iZ", -1j)], 1), + ([("Z", 1 + 2j), ("Z", -2j)], 1), + ([("Z", 1e-11)], 1e-11), + ]: + h = Hamiltonian(1) + for label, coeff in terms: + h.add_term(PauliString.from_str(label), coeff) + assert h.expectation_statevector(Statevector(1)) == pytest.approx( + expected, abs=1e-14 + ) + assert h.expectation_density_matrix(DensityMatrix(1)) == pytest.approx( + expected, abs=1e-14 + ) + assert h.expectation_probs( + [(PauliString.from_str("Z"), {"0": 1.0})] + ) == pytest.approx(expected, abs=1e-14) + + +def test_pauli_expectations_against_independent_dense_matrices(): + rng = np.random.default_rng(7451) + matrices = { + "I": np.eye(2), + "X": np.array([[0, 1], [1, 0]]), + "Y": np.array([[0, -1j], [1j, 0]]), + "Z": np.diag([1, -1]), + } + for n in [1, 2, 3]: + psi = rng.normal(size=2**n) + 1j * rng.normal(size=2**n) + psi /= np.linalg.norm(psi) + sv = Statevector.from_state(n, psi) + rho = 0.7 * np.outer(psi, psi.conj()) + 0.3 * np.eye(2**n) / 2**n + dm = DensityMatrix.from_density_matrix(n, rho.flatten()) + for labels in itertools.product("IXYZ", repeat=n): + matrix = np.array([[1]]) + for label in labels: + matrix = np.kron(matrix, matrices[label]) + for sign in [1, -1]: + p = PauliString.from_str(("-" if sign == -1 else "") + "".join(labels)) + assert sv.expectation(p) == pytest.approx( + sign * np.vdot(psi, matrix @ psi).real, abs=1e-12 + ) + assert dm.expectation(p) == pytest.approx( + sign * np.trace(rho @ matrix).real, abs=1e-12 + ) + + +@pytest.mark.parametrize("p", [0, 0.25, 1]) +def test_identity_noise_sparse_labels(p): + model = NoiseModel() + model.add_single_qubit_error(StandardGate.I, 5, SingleQubitNoise.bit_flip(p)) + for count in [1, 2, 3]: + c = Circuit([Qubit(12), Qubit(5)]) + for _ in range(count): + c.i(Qubit(5)) + flipped = (1 - (1 - 2 * p) ** count) / 2 + assert DensityMatrixNoise.from_circuit( + c, model + ).probabilities() == pytest.approx([1 - flipped, 0, flipped, 0]) + + +@pytest.mark.parametrize("symbolic", [False, True]) +@pytest.mark.parametrize("with_gates", [False, True]) +def test_zne_preserves_phase_and_parameter_binding(symbolic, with_gates): + c = Circuit([Qubit(5)]) + c.set_global_phase(Parameter("phi") if symbolic else 0.37) + if with_gates: + c.h(Qubit(5)) + c.t(Qubit(5)) + expected = circuit_to_matrix(c.assign_parameters({"phi": 0.37})) + for selection in [None, [], [Instruction.from_standard_gate(StandardGate.H)]]: + for folded in ZNEMitigation(c, [0, 1, 2]).fold_circuits(selection): + np.testing.assert_allclose( + circuit_to_matrix(folded.assign_parameters({"phi": 0.37})), + expected, + atol=1e-12, + ) + + +def test_renyi_known_nondiagonal_spectrum(): + # Rotated mixed state: eigenvalues stay known without a reference eigensolver. + spectrum = np.array([0.8, 0.2]) + u = np.array([[1, 1j], [1j, 1]]) / np.sqrt(2) + rho = u @ np.diag(spectrum) @ u.conj().T + dm = DensityMatrix.from_density_matrix(1, rho.flatten()) + shannon = -np.sum(spectrum * np.log2(spectrum)) + for alpha in [0.1, 0.5, 1 - 1e-12, 1, 1 + 1e-12, 2, 20, float("inf")]: + if abs(alpha - 1) < 1e-8: + expected = shannon + elif np.isinf(alpha): + expected = -np.log2(max(spectrum)) + else: + expected = np.log2(np.sum(spectrum**alpha)) / (1 - alpha) + assert entropy.renyi_entropy(dm, alpha) == pytest.approx(expected, abs=1e-10) + + +@pytest.mark.parametrize("bad", [complex(float("nan"), 0), complex(0, float("inf"))]) +def test_nonfinite_observable_coefficients(bad): + h = Hamiltonian(1) + h.add_term(PauliString.from_str("Z"), bad) + for call in [ + lambda: h.expectation_statevector(Statevector(1)), + lambda: h.expectation_density_matrix(DensityMatrix(1)), + lambda: h.expectation_probs([(PauliString.from_str("Z"), {"0": 1.0})]), + ]: + with pytest.raises(ValueError, match="finite"): + call() + + +@pytest.mark.parametrize("alpha", [0.01, 0.1, 0.5, 1, 2, float("inf")]) +def test_renyi_nondiagonal_pure_state_is_zero(alpha): + psi = np.array([1, 2, 3, 4], dtype=complex) / np.sqrt(30) + dm = DensityMatrix.from_state(2, psi) + assert entropy.renyi_entropy(dm, alpha) == pytest.approx(0, abs=1e-10) + + +@pytest.mark.parametrize("alpha", [0.01, 0.1, 0.5, 1, 2, float("inf")]) +def test_renyi_rank_deficient_spectrum_is_invariant_under_rotation(alpha): + spectrum = np.array([0.8, 0.2, 0, 0]) + indices = np.arange(4) + u = np.exp(2j * np.pi * np.outer(indices, indices) / 4) / 2 + expected = ( + -np.sum(spectrum[:2] * np.log2(spectrum[:2])) + if alpha == 1 + else -np.log2(0.8) + if np.isinf(alpha) + else np.log2(np.sum(spectrum[:2] ** alpha)) / (1 - alpha) + ) + for rho in [np.diag(spectrum), u @ np.diag(spectrum) @ u.conj().T]: + dm = DensityMatrix.from_density_matrix(2, rho.astype(complex).flatten()) + assert entropy.renyi_entropy(dm, alpha) == pytest.approx(expected, abs=1e-10) + + +@pytest.mark.parametrize("bad", [float("nan"), float("inf"), -float("inf")]) +def test_variance_rejects_nonfinite_coefficients(bad): + for coeff in [complex(bad, 0), complex(0, bad)]: + h = Hamiltonian(1) + h.add_term(PauliString.from_str("Z"), coeff) + with pytest.raises(ValueError, match="finite"): + h.variance_statevector(Statevector(1)) + + +def test_variance_validates_merged_coefficients_and_preserves_small_terms(): + h = Hamiltonian(1) + for _ in range(2): + h.add_term(PauliString.from_str("Z"), np.finfo(float).max) + with pytest.raises(ValueError, match="finite"): + h.variance_statevector(Statevector(1)) + for terms, expected in [ + ([("iX", -1j)], 1), + ([("X", 1 + 2j), ("X", -2j)], 1), + ([("X", 1e-11)], 1e-22), + ]: + h = Hamiltonian(1) + for label, coeff in terms: + h.add_term(PauliString.from_str(label), coeff) + assert h.variance_statevector(Statevector(1)) == pytest.approx( + expected, rel=1e-12, abs=1e-34 + ) + invalid = Hamiltonian.from_pauli(PauliString.from_str("iZ")) + with pytest.raises(ValueError, match="Hermitian"): + invalid.variance_statevector(Statevector(1)) + with pytest.raises(ValueError, match="Qubit count mismatch"): + invalid.variance_statevector(Statevector(2)) diff --git a/crates/binding-python/tests/qis/test_stabilizer.py b/crates/binding-python/tests/qis/test_stabilizer.py index 8114759d..7aa02ba5 100644 --- a/crates/binding-python/tests/qis/test_stabilizer.py +++ b/crates/binding-python/tests/qis/test_stabilizer.py @@ -272,3 +272,19 @@ def test_two_qubit_gates_reject_duplicate_qubits(self): with pytest.raises(ValueError): state.apply_swap(1, 1) + + +@pytest.mark.parametrize("theta", [0.0, 0.37, math.pi / 2]) +@pytest.mark.parametrize("entrypoint", ["from_circuit", "apply_circuit", "run_circuit"]) +def test_controlled_gphase_returns_normal_unsupported_error(theta, entrypoint): + from cqlib.circuit.gates import GPhase + + circuit = Circuit([12]) + circuit.append_mc_gate(GPhase(theta).control(1), [12]) + execute = ( + StabilizerState(1).apply_circuit + if entrypoint == "apply_circuit" + else getattr(StabilizerState, entrypoint) + ) + with pytest.raises(ValueError, match="Controlled-GPhase.*not supported"): + execute(circuit) diff --git a/crates/binding-python/tests/visualization/test_visualization.py b/crates/binding-python/tests/visualization/test_visualization.py index 42b1098d..331cf9d5 100644 --- a/crates/binding-python/tests/visualization/test_visualization.py +++ b/crates/binding-python/tests/visualization/test_visualization.py @@ -23,6 +23,7 @@ import subprocess import tempfile import zlib +from xml.etree import ElementTree import pytest import resvg_py @@ -641,6 +642,34 @@ def test_state_visualization_accepts_density_matrix(): assert vis.plot_state_paulivec(sv) == vis.plot_state_paulivec(dm) +@pytest.mark.parametrize("state_type", [Statevector, DensityMatrix]) +@pytest.mark.parametrize("reverse_bits", [False, True]) +def test_paulivec_labels_identify_the_correct_qubit(state_type, reverse_bits): + """The displayed IX bar measures q0 unless display bits are reversed.""" + state = state_type(2) + state.apply_h(0) + svg = vis.plot_state_paulivec(state, reverse_bits=reverse_bits) + elements = list(ElementTree.fromstring(svg)) + bars = { + element.text: elements[index - 1].attrib + for index, element in enumerate(elements) + if element.tag.endswith("text") + and element.text in {"II", "IX", "XI", "IZ", "ZI"} + } + one_y = float(bars["II"]["y"]) + one_height = float(bars["II"]["height"]) + assert one_height > 1.0 + for label, expected in [("IX", 1), ("XI", 0), ("IZ", 0), ("ZI", 1)]: + displayed = label[::-1] if reverse_bits else label + y = float(bars[displayed]["y"]) + height = float(bars[displayed]["height"]) + if expected: + assert (y, height) == (one_y, one_height) + else: + assert height == 1.0 + assert y == pytest.approx(one_y + one_height) + + def test_state_visualization_validates_python_inputs(): """Invalid Python inputs should fail with clear ValueError messages.""" with pytest.raises(ValueError, match="exactly 3"): diff --git a/crates/cqlib-core/Cargo.toml b/crates/cqlib-core/Cargo.toml index 93c46666..257f8a3c 100644 --- a/crates/cqlib-core/Cargo.toml +++ b/crates/cqlib-core/Cargo.toml @@ -21,7 +21,6 @@ categories = [ "science", "simulation", "algorithms", - "science::physics", "data-structures" ] include = [ diff --git a/crates/cqlib-core/README.md b/crates/cqlib-core/README.md index 913e85e3..98732e2a 100644 --- a/crates/cqlib-core/README.md +++ b/crates/cqlib-core/README.md @@ -14,13 +14,13 @@ Add the crate to your project: ```toml [dependencies] -cqlib-core = "0.1.0-beta.1" +cqlib-core = "0.1.0-beta.7" ``` Or use Cargo: ```shell -cargo add cqlib-core@0.1.0-beta.1 +cargo add cqlib-core@0.1.0-beta.7 ``` ## Quick start @@ -77,7 +77,8 @@ assert!(bound.parameters().is_empty()); - **Simulation** — Statevector, density-matrix, noisy density-matrix, and stabilizer simulation - **Quantum information** — Pauli operators, Hamiltonians, observables, - evolution, metrics, and entropy functions + evolution, fermionic algebra, excitation generators, Jordan–Wigner mapping, + metrics, and entropy functions - **Error mitigation** — Zero-noise extrapolation and virtual distillation - **Interchange formats** — OpenQASM 2, OpenQASM 3, and QCIS - **Visualization** — Text and SVG circuit rendering plus state and result plots diff --git a/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution.rs b/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution.rs index e9096ac2..27f2b4a8 100644 --- a/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution.rs +++ b/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution.rs @@ -181,7 +181,7 @@ pub struct EvolutionInfo { /// /// # Requirements /// -/// - The Hamiltonian must be **Hermitian**: after calling `simplify()`, all +/// - The Hamiltonian must be **Hermitian**: after phase normalization and merging, all /// coefficients must have negligible imaginary part ($|\text{Im}(c_k)| < 10^{-10}$). /// - The Hamiltonian must be **non-empty**. /// - For [`EvolutionStrategy::Exact`], all terms must mutually commute. @@ -232,7 +232,7 @@ pub struct PauliEvolutionAnsatz { /// The simplified Hamiltonian (normalized, de-duplicated). /// /// **Invariant**: always in simplified form (phases absorbed, duplicates merged, - /// near-zero terms removed). Any future mutating API must re-run `simplify()` and + /// exact-zero terms removed). Any future mutating API must re-run normalization and /// re-validate Hermiticity before updating this field. hamiltonian: Hamiltonian, /// Cached result of `hamiltonian.all_terms_commute()`, computed once in `new()`. @@ -252,20 +252,20 @@ pub struct PauliEvolutionAnsatz { impl PauliEvolutionAnsatz { /// Creates a new ansatz from a Hamiltonian. /// - /// Internally calls [`Hamiltonian::simplify`] to normalize the Hamiltonian - /// (merge duplicate terms, absorb phases into coefficients, remove near-zero terms) - /// before any further processing. + /// Validates and normalizes the Hamiltonian (merges duplicate terms, absorbs + /// phases into coefficients and removes exact zeros). Small nonzero coefficients + /// are retained, matching the numeric Hamiltonian evolution APIs. Imaginary + /// roundoff residuals of magnitude at most `1e-10` are projected to zero. /// /// The default strategy is [`EvolutionStrategy::Auto`] with `steps = 1`. /// /// # Errors /// /// Returns [`QisError::InvalidParameterValue`] if the Hamiltonian is empty after - /// simplification, or [`QisError::NotHermitian`] if any coefficient has a non-zero - /// imaginary part after simplification. + /// real projection, or [`QisError::NotHermitian`] if any merged coefficient + /// has an imaginary part of magnitude greater than `1e-10`. pub fn new(hamiltonian: Hamiltonian) -> Result { - let mut h = hamiltonian; - h.simplify(); + let h = hamiltonian.normalized_hermitian()?; if h.terms.is_empty() { return Err(QisError::InvalidParameterValue( @@ -274,15 +274,6 @@ impl PauliEvolutionAnsatz { )); } - // Hermitian check: all coefficients must be real after simplify(). - // simplify() absorbs any PauliString phase into the coefficient, so a - // term like (0.5) * (-iY) becomes (-0.5i) * Y — which fails this check. - for (_pauli, coeff) in &h.terms { - if coeff.im.abs() > 1e-10 { - return Err(QisError::NotHermitian); - } - } - // Cache commutativity once; reused by validate(), evolution_info(), build_circuit(). let all_terms_commute = h.all_terms_commute(); diff --git a/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution_test.rs b/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution_test.rs index 024615a4..1b09d36b 100644 --- a/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution_test.rs +++ b/crates/cqlib-core/src/circuit/ansatz/hamiltonian_evolution_test.rs @@ -26,7 +26,7 @@ use ndarray::Array2; use num_complex::Complex64; use crate::circuit::ansatz::Ansatz; -use crate::circuit::circuit_to_matrix; +use crate::circuit::circuit_to_matrix::circuit_to_matrix; use crate::qis::evolution::TrotterMode; use crate::qis::hamiltonian::Hamiltonian; @@ -86,6 +86,120 @@ fn circuit_matrix_at_t( circuit_to_matrix(&bound, None).unwrap() } +#[test] +fn small_coefficients_survive_symbolic_evolution_and_trotter_scaling() { + for coefficient in [1e-16, 1e-12, -1e-16] { + for pauli in ["Z", "I", "X", "Y"] { + let h = Hamiltonian::from_list(vec![( + pauli.parse().unwrap(), + Complex64::new(coefficient, 0.0), + )]) + .unwrap(); + let time = 1.0 / coefficient; + let expected = matrix_exp_iht(&hamiltonian_matrix(&h), time); + for strategy in [ + EvolutionStrategy::Exact, + EvolutionStrategy::Auto { steps: 512 }, + EvolutionStrategy::Trotter { + mode: TrotterMode::FirstOrder, + steps: 512, + }, + EvolutionStrategy::Trotter { + mode: TrotterMode::SecondOrder, + steps: 512, + }, + EvolutionStrategy::Trotter { + mode: TrotterMode::Randomized(7), + steps: 512, + }, + ] { + let ansatz = PauliEvolutionAnsatz::new(h.clone()) + .unwrap() + .with_strategy(strategy.clone()); + let circuit = ansatz.build_circuit("small").unwrap(); + assert_eq!(circuit.symbols().len(), ansatz.num_parameters()); + assert!(circuit.symbols().contains("small_t")); + // An incomplete binding must preserve the time dependence too. + let partial = circuit.assign_parameters(&Some(HashMap::new())).unwrap(); + assert!(partial.symbols().contains("small_t")); + let bound = partial + .assign_parameters(&Some(HashMap::from([("small_t", time)]))) + .unwrap(); + assert!(frob_dist(&circuit_to_matrix(&bound, None).unwrap(), &expected) < 1e-10); + let actual = circuit_matrix_at_t(&ansatz, "small", "small_t", time); + assert!( + frob_dist(&actual, &expected) < 1e-10, + "{pauli}, coefficient={coefficient}, strategy={strategy:?}" + ); + } + } + } +} + +#[test] +fn imaginary_residuals_are_projected_before_ansatz_zero_check() { + for pauli in ["I", "Z"] { + let h = Hamiltonian::from_list(vec![(pauli.parse().unwrap(), Complex64::new(0.0, 1e-12))]) + .unwrap(); + assert!(matches!( + PauliEvolutionAnsatz::new(h), + Err(crate::qis::QisError::InvalidParameterValue(_)) + )); + } + + // Real parts cancel, leaving only an accepted imaginary roundoff residual. + let h = Hamiltonian::from_list(vec![ + ("Z".parse().unwrap(), Complex64::new(1.0, 1e-12)), + ("Z".parse().unwrap(), Complex64::new(-1.0, 0.0)), + ]) + .unwrap(); + assert!(PauliEvolutionAnsatz::new(h).is_err()); + + // Projection must retain even a very small nonzero real generator. + let h = + Hamiltonian::from_list(vec![("Z".parse().unwrap(), Complex64::new(1e-16, 1e-12))]).unwrap(); + let ansatz = PauliEvolutionAnsatz::new(h).unwrap(); + assert_eq!(ansatz.hamiltonian.terms[0].1, Complex64::new(1e-16, 0.0)); + let actual = circuit_matrix_at_t(&ansatz, "residual", "residual_t", 1e16); + let expected = matrix_exp_iht(&hamiltonian_matrix(&ansatz.hamiltonian), 1e16); + assert!(frob_dist(&actual, &expected) < 1e-12); +} + +#[test] +fn mapped_small_number_operator_retains_time_and_global_phase() { + use crate::qis::fermion::{FermionToQubitMapper, FermionicOp, JordanWignerMapper}; + + let op = FermionicOp::number(1, 0) + .unwrap() + .scaled(Complex64::new(1e-16, 0.0)) + .unwrap(); + let h = JordanWignerMapper::new().map_operator(&op).unwrap(); + let ansatz = PauliEvolutionAnsatz::new(h).unwrap(); + let actual = circuit_matrix_at_t(&ansatz, "number", "number_t", 1e16); + // exp(-i n): vacuum has phase 1 and the occupied state has phase exp(-i). + let mut expected = Array2::::eye(2); + expected[[1, 1]] = Complex64::new(0.0, -1.0).exp(); + assert!(frob_dist(&actual, &expected) < 1e-12); +} + +#[test] +fn small_noncommuting_auto_evolution_matches_numeric_trotter() { + let h = Hamiltonian::from_list(vec![ + ("X".parse().unwrap(), Complex64::new(1e-12, 0.0)), + ("Z".parse().unwrap(), Complex64::new(-1e-12, 0.0)), + ]) + .unwrap(); + let numeric = h + .to_trotter_circuit(1e12, 512, TrotterMode::FirstOrder) + .unwrap(); + let expected = circuit_to_matrix(&numeric, None).unwrap(); + let ansatz = PauliEvolutionAnsatz::new(h) + .unwrap() + .with_strategy(EvolutionStrategy::Auto { steps: 512 }); + let actual = circuit_matrix_at_t(&ansatz, "auto", "auto_t", 1e12); + assert!(frob_dist(&actual, &expected) < 1e-12); +} + #[test] fn test_new_simplifies_hamiltonian() { // Add two identical terms: should merge into one with double coefficient diff --git a/crates/cqlib-core/src/circuit/circuit_classical.rs b/crates/cqlib-core/src/circuit/circuit_classical.rs index 7f51423c..8621fb23 100644 --- a/crates/cqlib-core/src/circuit/circuit_classical.rs +++ b/crates/cqlib-core/src/circuit/circuit_classical.rs @@ -411,7 +411,9 @@ use crate::circuit::control_flow::{ }; use crate::circuit::error::CircuitError; use crate::circuit::gate::instruction::Instruction; -use crate::circuit::{ClassicalDataOp, ClassicalType, ClassicalValue, ClassicalVar, Measurement}; +use crate::circuit::{ + CircuitParam, ClassicalDataOp, ClassicalType, ClassicalValue, ClassicalVar, Measurement, +}; use std::sync::Arc; #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -467,14 +469,17 @@ impl SwitchBuilder<'_> { } } -#[derive(Debug, Clone, Copy)] +/// Restores appended builder state and the previous phase, not edits to existing entries. +#[derive(Debug, Clone)] pub(super) struct CircuitCheckpoint { data_len: usize, + qubit_len: usize, parameter_len: usize, symbol_len: usize, classical_var_len: usize, classical_value_len: usize, control_scope_len: usize, + global_phase: CircuitParam, } /// Opaque rollback token for callback-driven control-flow construction. @@ -539,17 +544,21 @@ impl Circuit { pub(super) fn checkpoint(&self) -> CircuitCheckpoint { CircuitCheckpoint { data_len: self.data.len(), + qubit_len: self.qubits.len(), parameter_len: self.parameters.len(), symbol_len: self.symbols.len(), classical_var_len: self.classical_vars.len(), classical_value_len: self.classical_values.len(), control_scope_len: self.control_scope_stack.len(), + global_phase: self.global_phase.clone(), } } pub(super) fn rollback_to(&mut self, checkpoint: CircuitCheckpoint) { Arc::make_mut(&mut self.data).truncate(checkpoint.data_len); + self.qubits.truncate(checkpoint.qubit_len); self.parameters.truncate(checkpoint.parameter_len); + self.global_phase = checkpoint.global_phase; self.symbols.truncate(checkpoint.symbol_len); self.classical_vars.truncate(checkpoint.classical_var_len); self.classical_values diff --git a/crates/cqlib-core/src/circuit/circuit_impl.rs b/crates/cqlib-core/src/circuit/circuit_impl.rs index 3cfffaf6..15958783 100644 --- a/crates/cqlib-core/src/circuit/circuit_impl.rs +++ b/crates/cqlib-core/src/circuit/circuit_impl.rs @@ -2255,6 +2255,8 @@ impl Circuit { /// the result is `Rx(beta+1)`. /// 2. **Qubit Mapping**: Virtual qubits in the sub-circuit definition are mapped to the /// physical qubits in the parent circuit. + /// 3. **Global Phase**: Each sub-circuit's phase is substituted using its call arguments + /// and accumulated into the flattened circuit, including empty definitions. /// /// # Returns /// @@ -2263,8 +2265,9 @@ impl Circuit { /// /// # Errors /// - /// Returns [`CircuitError::UnresolvedParameter`] if a symbolic parameter in a sub-circuit - /// or control flow body cannot be evaluated to a concrete value. + /// Returns an error if a fully resolved parameter or accumulated global phase is invalid, + /// or if the circuit contains unsupported classical control. Unbound symbolic parameters + /// and phases are preserved. pub fn decompose(&self) -> Result { let mut new_circuit = Circuit::from_qubits(self.qubits()).unwrap(); new_circuit.classical_vars = self.classical_vars.clone(); @@ -2367,6 +2370,21 @@ impl Circuit { } } + // Phase is circuit metadata, so it must be accumulated even when + // the definition has no operations. Each gate application adds it once. + if cg.circuit.circuit.global_phase_param() != &CircuitParam::Fixed(0.0) { + let phase = + Self::apply_param_map(cg.circuit.circuit.global_phase(), &next_param_map); + if phase.get_symbols().is_empty() { + phase.evaluate(&None)?; + } + let phase = target_circuit.global_phase() + phase; + if phase.get_symbols().is_empty() { + phase.evaluate(&None)?; + } + target_circuit.set_global_phase(phase); + } + // Qubit Map: Inner Qubit -> Outer Qubit // op.qubits are the qubits in 'context_circuit' that the gate acts on. // We need to map them through 'qubit_map' to get 'target_circuit' qubits. @@ -2471,6 +2489,8 @@ impl Circuit { /// /// Parameters that remain symbolic are simplified and re-interned in the /// returned circuit. The original circuit is not modified. + /// Internal classical references are remapped to the returned circuit's + /// identity; handles from the original circuit remain owned by it. /// /// # Errors /// @@ -2495,6 +2515,29 @@ impl Circuit { new_circuit.classical_vars = self.classical_vars.clone(); new_circuit.classical_values = self.classical_values.clone(); + let var_map = self + .classical_vars + .iter() + .enumerate() + .map(|(index, ty)| { + ( + ClassicalVar::new(self.circuit_id, index as u32, *ty), + ClassicalVar::new(new_circuit.circuit_id, index as u32, *ty), + ) + }) + .collect(); + let value_map = self + .classical_values + .iter() + .enumerate() + .map(|(index, ty)| { + ( + ClassicalValue::new(self.circuit_id, index as u32, *ty), + ClassicalValue::new(new_circuit.circuit_id, index as u32, *ty), + ) + }) + .collect(); + // Map from old parameter index to new CircuitParam (either Fixed or Index) let mut index_map: Vec = Vec::with_capacity(self.parameters.len()); @@ -2529,20 +2572,23 @@ impl Circuit { } } - // Remap operations to use new parameter indices or fixed values + // Remap parameter indices and all classical references in the same pass. let new_data = Arc::make_mut(&mut new_circuit.data); new_data.reserve(self.data.len()); for op in self.data.iter() { - let mut new_op = op.clone(); - for p in &mut new_op.params { - if let CircuitParam::Index(old_idx) = p { - *p = index_map + new_data.push(Self::remap_operation( + op, + &|qubit| Ok(qubit), + &|param| match param { + CircuitParam::Index(old_idx) => index_map .get(*old_idx as usize) .cloned() - .ok_or(CircuitError::InvalidParameterIndex(*old_idx))?; - } - } - new_data.push(new_op); + .ok_or(CircuitError::InvalidParameterIndex(*old_idx)), + CircuitParam::Fixed(value) => Ok(CircuitParam::Fixed(*value)), + }, + &var_map, + &value_map, + )?); } // Remap global phase @@ -2763,21 +2809,25 @@ impl Circuit { /// [`Qubit`] IDs. /// Circuit-local classical variables and values from `other` are appended to `self`'s /// classical tables, and all classical data/control references inside copied operations are - /// remapped to those new local IDs. + /// remapped to those new local IDs. The identity of `self` and its existing classical + /// handles are preserved. If composition returns an error, `self` is unchanged. /// /// # Arguments /// /// * `other` - The circuit to compose into this circuit. /// * `qubits_map` - An optional slice mapping qubits from `other` to qubits in `self`. - /// - If `Some(mapping)` is provided, each qubit in `other` (in their natural iteration order) - /// is mapped to the corresponding qubit in `mapping`. + /// - If `Some(mapping)` is provided, each qubit in `other` (in insertion order) + /// is mapped to the corresponding qubit in `mapping`. Target qubits must be distinct, + /// including targets corresponding to idle source qubits. /// - If `None` is provided, qubits are mapped by ID. IDs not already present in `self` are /// appended, while matching IDs reuse the existing qubits. /// /// # Returns /// /// * `Ok(())` - If composition succeeds. - /// * `Err(CircuitError)` - If the mapping is invalid (wrong length or non-existent qubits). + /// * `Err(CircuitError)` - If the mapping has the wrong length, contains duplicate targets + /// ([`CircuitError::DuplicateQubits`]), references non-existent qubits, or stored circuit + /// references cannot be remapped. /// /// # Examples /// @@ -2816,6 +2866,9 @@ impl Circuit { actual: mapping.len(), }); } + if !Self::check_qubits_unique(mapping) { + return Err(CircuitError::DuplicateQubits); + } // Build map and validate target qubits exist in self let mut map = HashMap::with_capacity(mapping.len()); @@ -2830,8 +2883,6 @@ impl Circuit { // No explicit mapping: merge qubits by ID. let mut map = HashMap::with_capacity(other.qubits.len()); for other_qubit in other.qubits.iter() { - // Existing IDs are reused; new IDs preserve `other`'s insertion order. - self.qubits.insert(*other_qubit); map.insert(*other_qubit, *other_qubit); } map @@ -2857,10 +2908,20 @@ impl Circuit { ); } - // Merge parameters and build index mapping + // Stage only new parameters: remapping and phase resolution can still fail. + // Keep the existing registry read-only rather than copying it on each composition. + // Staged indices follow the existing entries and remain valid after the final append. + let parameter_base = self.parameters.len(); + let mut new_parameters = IndexSet::new(); + let mut new_symbols = IndexSet::new(); let mut param_index_map: Vec = Vec::with_capacity(other.parameters.len()); for param in other.parameters.iter() { - let (idx, _) = self.add_parameter(param.clone()); + let idx = if let Some(idx) = self.parameters.get_index_of(param) { + idx + } else { + new_symbols.extend(param.get_symbols()); + parameter_base + new_parameters.insert_full(param.clone()).0 + }; param_index_map.push(CircuitParam::Index(idx as u32)); } @@ -2878,56 +2939,32 @@ impl Circuit { }) .collect::, _>>()?; - // Merge global phase (if both have fixed values, add them; otherwise keep symbolic) - self.global_phase = match (self.global_phase.clone(), other.global_phase.clone()) { + // Resolve against the original registries. A new source parameter must not make an + // invalid pre-existing destination index appear valid in the merged registry. + let global_phase = match (&self.global_phase, &other.global_phase) { (CircuitParam::Fixed(a), CircuitParam::Fixed(b)) => CircuitParam::Fixed(a + b), - (CircuitParam::Fixed(a), CircuitParam::Index(idx)) => { - // Add fixed value to symbolic parameter - let sym_param = other - .parameters - .get_index(idx as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx))?; - let new_expr = Parameter::from(a) + sym_param; - let (new_idx, _) = self.parameters.insert_full(new_expr); - CircuitParam::Index(new_idx as u32) - } - (CircuitParam::Index(idx), CircuitParam::Fixed(b)) => { - // Add symbolic parameter to fixed value - let sym_param = self - .parameters - .get_index(idx as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx))?; - let new_expr = sym_param + Parameter::from(b); - let (new_idx, _) = self.parameters.insert_full(new_expr); - CircuitParam::Index(new_idx as u32) - } - (CircuitParam::Index(idx_a), CircuitParam::Index(idx_b)) => { - // Add two symbolic parameters - let param_a = self - .parameters - .get_index(idx_a as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx_a))?; - let param_b = other - .parameters - .get_index(idx_b as usize) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(idx_b))?; - // param_b needs to be merged into self's parameter set first - let (merged_b_idx, _) = self.parameters.insert_full(param_b); - let merged_b = self + _ => { + let new_expr = self.resolve_parameter(&self.global_phase)? + + other.resolve_parameter(&other.global_phase)?; + // Every symbol in the sum already belongs to one of the merged registries. + let new_idx = self .parameters - .get_index(merged_b_idx) - .cloned() - .ok_or(CircuitError::InvalidParameterIndex(merged_b_idx as u32))?; - let new_expr = param_a + merged_b; - let (new_idx, _) = self.parameters.insert_full(new_expr); + .get_index_of(&new_expr) + .unwrap_or_else(|| parameter_base + new_parameters.insert_full(new_expr).0); CircuitParam::Index(new_idx as u32) } }; + // Commit only after all fallible preparation succeeds. Preserve insertion order and + // the active control-builder scope, as well as all existing classical handle IDs. + if qubits_map.is_none() { + self.qubits.extend(other.qubits.iter().copied()); + } + if !new_parameters.is_empty() { + self.parameters.extend(new_parameters); + } + self.symbols.extend(new_symbols); + self.global_phase = global_phase; self.classical_vars .extend(other.classical_vars.iter().copied()); self.classical_values diff --git a/crates/cqlib-core/src/circuit/circuit_param.rs b/crates/cqlib-core/src/circuit/circuit_param.rs index 15721c06..01a8e308 100644 --- a/crates/cqlib-core/src/circuit/circuit_param.rs +++ b/crates/cqlib-core/src/circuit/circuit_param.rs @@ -102,8 +102,10 @@ impl ParameterValue { /// /// Fixed values use floating-point multiplication. Symbolic values use /// expression multiplication and remain `Param`, even if the resulting - /// expression is constant (including multiplication by zero). This method - /// does not explicitly evaluate, simplify, or canonicalize expressions. + /// expression is constant (including multiplication by zero). In affine + /// expressions with unresolved symbols, coefficients are preserved without + /// tolerance pruning. + /// This method does not explicitly evaluate or canonicalize expressions. /// Unlike converting a `Parameter` with `Into`, it does not fold constants /// into `Fixed` values. /// diff --git a/crates/cqlib-core/src/circuit/circuit_param_test.rs b/crates/cqlib-core/src/circuit/circuit_param_test.rs index 45690540..8a99fe28 100644 --- a/crates/cqlib-core/src/circuit/circuit_param_test.rs +++ b/crates/cqlib-core/src/circuit/circuit_param_test.rs @@ -59,6 +59,38 @@ fn scaled_constant_expressions_remain_param() { } } +#[test] +fn small_symbolic_scales_survive_canonicalization_and_substitution() { + let input = ParameterValue::Param(Parameter::symbol("theta")); + for factor in [1e-16, -1e-16, 1e-12 / 512.0, f64::from_bits(1)] { + let ParameterValue::Param(scaled) = input.scaled(factor) else { + panic!("symbolic input must remain Param"); + }; + let canonical = scaled.canonicalized().unwrap(); + assert!(canonical.get_symbols().contains("theta")); + assert_eq!( + canonical + .evaluate(&Some(HashMap::from([("theta", 1.0)]))) + .unwrap(), + factor + ); + + let renamed = canonical.replace("theta", Parameter::symbol("time")); + let rescaled = ParameterValue::Param(renamed).scaled(-0.5); + let ParameterValue::Param(rescaled) = rescaled else { + unreachable!() + }; + let canonical = rescaled.canonicalized().unwrap(); + let expected = factor * -0.5; + assert_eq!( + canonical + .evaluate(&Some(HashMap::from([("time", 1e16)]))) + .unwrap(), + expected * 1e16 + ); + } +} + #[test] fn scaled_rejects_non_finite_factors_for_both_variants() { for input in [ diff --git a/crates/cqlib-core/src/circuit/circuit_test.rs b/crates/cqlib-core/src/circuit/circuit_test.rs index d8f476c8..c42c81b5 100644 --- a/crates/cqlib-core/src/circuit/circuit_test.rs +++ b/crates/cqlib-core/src/circuit/circuit_test.rs @@ -20,13 +20,16 @@ use crate::circuit::gate::{ }; use crate::circuit::operation::ValueOperation; use crate::circuit::parameter::Parameter; +use crate::circuit::symbolic_matrix::{circuit_to_symbolic_matrix, evaluate_symbolic_matrix}; +use crate::circuit::test_utils::assert_matrix_approx_eq; use crate::circuit::{ ClassicalControlOp, ClassicalExpr, ClassicalType, ClassicalValue, ClassicalVar, ControlBody, - IfOp, Operation, SwitchCase, SwitchOp, ValueClassicalControlOp, ValueControlBody, - ValueInstruction, WhileOp, + ExternalControlScope, IfOp, Operation, SwitchCase, SwitchOp, ValueClassicalControlOp, + ValueControlBody, ValueInstruction, WhileOp, circuit_to_matrix, }; +use crate::qis::{RuntimeValue, StabilizerState, Statevector}; use smallvec::smallvec; -use std::collections::HashSet; +use std::collections::{HashMap, HashSet}; use std::f64::consts::PI; use std::sync::Arc; @@ -1239,8 +1242,6 @@ fn test_to_gate_and_circuit_gate() { #[test] fn test_assign_parameters() { - use std::collections::HashMap; - let mut circuit = Circuit::new(2); let q0 = Qubit::new(0); let a = Parameter::symbol("a"); @@ -1303,6 +1304,202 @@ fn test_assign_parameters() { } } +#[test] +fn test_assign_parameters_preserves_measurement_execution() { + for with_store in [false, true] { + let q0 = Qubit::new(0); + let mut source = Circuit::new(1); + source.rx(q0, "theta").unwrap(); + source.rz(q0, "phi").unwrap(); + source.set_global_phase(Parameter::symbol("theta")); + let measured = source.measure(q0).unwrap(); + if with_store { + let target = source.var(ClassicalType::Bit); + source.store(target, measured.expr()).unwrap(); + } + let before = format!("{source:?}"); + let full = Some(HashMap::from([("theta", 0.731), ("phi", 0.317)])); + + for bindings in [ + None, + Some(HashMap::new()), + Some(HashMap::from([("theta", 0.731)])), + full.clone(), + ] { + let bound = source.assign_parameters(&bindings).unwrap(); + bound.validate().unwrap(); + assert_ne!(bound.id(), source.id()); + assert_eq!(bound.classical_values(), source.classical_values()); + assert!(matches!( + bound.validate_classical_expr(&measured.expr()), + Err(CircuitError::ForeignClassicalHandle { .. }) + )); + bound.clone().validate().unwrap(); + bound.decompose().unwrap().validate().unwrap(); + + if bindings.as_ref().is_some_and(|map| map.len() == 1) { + assert_eq!(bound.data[0].params[0], CircuitParam::Fixed(0.731)); + assert_eq!(bound.data[1].params[0], CircuitParam::Index(0)); + assert_eq!(bound.parameters.len(), 1); + assert!(bound.symbols.contains("phi")); + assert!(!bound.symbols.contains("theta")); + assert_eq!(*bound.global_phase_param(), CircuitParam::Fixed(0.731)); + } + + let complete = bound.assign_parameters(&full).unwrap(); + complete.validate().unwrap(); + assert_ne!(complete.id(), bound.id()); + let actual = Statevector::from_circuit(&complete).unwrap(); + let mut expected = Circuit::new(1); + expected.rx(q0, 0.731).unwrap(); + expected.rz(q0, 0.317).unwrap(); + expected.set_global_phase(Parameter::from(0.731)); + let expected = Statevector::from_circuit(&expected).unwrap(); + for (actual, expected) in actual.data().iter().zip(expected.data()) { + assert!((*actual - *expected).norm() < 1e-12); + } + assert_eq!(format!("{source:?}"), before); + } + } +} + +#[test] +fn test_assign_parameters_executes_classical_dataflow() { + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + for multibit in [false, true] { + let mut source = Circuit::new(2); + source.set_global_phase(Parameter::symbol("theta") + Parameter::symbol("phi")); + source.x(q0).unwrap(); + let measured = if multibit { + source.measure_bits([q1, q0]).unwrap() + } else { + source.measure(q0).unwrap() + }; + let first = source.var(measured.ty()); + let second = source.var(measured.ty()); + source.store(first, measured.expr()).unwrap(); + source.store(second, first.expr()).unwrap(); + let flag = source.var(ClassicalType::Bool); + // A nested expression must remap both immutable values and mutable vars. + source + .store( + flag, + !ClassicalExpr::eq(second.expr(), measured.expr()).unwrap(), + ) + .unwrap(); + let before = format!("{source:?}"); + + for bindings in [ + None, + Some(HashMap::new()), + Some(HashMap::from([("theta", 0.731)])), + Some(HashMap::from([("theta", 0.731), ("phi", 0.317)])), + ] { + let bound = source.assign_parameters(&bindings).unwrap(); + bound.validate().unwrap(); + assert_eq!(bound.classical_vars(), source.classical_vars()); + assert_eq!(bound.classical_values(), source.classical_values()); + assert!(matches!( + bound.validate_classical_var(first), + Err(CircuitError::ForeignClassicalHandle { .. }) + )); + // Complete partial/absent bindings before runtime execution. + let mut complete = bound + .assign_parameters(&Some(HashMap::from([("theta", 0.731), ("phi", 0.317)]))) + .unwrap(); + complete.validate().unwrap(); + let execution = StabilizerState::run_circuit(&complete).unwrap(); + for operation in complete.operations() { + match &operation.instruction { + Instruction::ClassicalData(ClassicalDataOp::MeasureBit { result }) => { + assert_eq!( + execution.classical.value(*result), + Some(&RuntimeValue::Bit(true)) + ); + } + Instruction::ClassicalData(ClassicalDataOp::MeasureBits { result }) => { + assert_eq!( + execution + .classical + .value(*result) + .unwrap() + .to_bitstring() + .unwrap(), + "10" + ); + } + Instruction::ClassicalData(ClassicalDataOp::Store { target, .. }) => { + let actual = execution.classical.var(*target).unwrap(); + if target.ty() == ClassicalType::Bool { + assert_eq!(*actual, RuntimeValue::Bool(false)); + } else if multibit { + assert_eq!(actual.to_bitstring().unwrap(), "10"); + } else { + assert_eq!(*actual, RuntimeValue::Bit(true)); + } + } + _ => {} + } + } + assert!(execution.classical.value(measured.value()).is_none()); + assert!(execution.classical.var(first).is_none()); + complete.clone().validate().unwrap(); + complete.decompose().unwrap().validate().unwrap(); + let fresh = complete.var(ClassicalType::Bit); + complete + .store(fresh, ClassicalExpr::bit_literal(false)) + .unwrap(); + complete.validate().unwrap(); + assert_eq!(format!("{source:?}"), before); + } + } +} + +#[test] +fn test_assign_parameters_remaps_store_without_measurement() { + let mut source = Circuit::new(1); + let unused = source.var(ClassicalType::Bit); + let target = source.var(ClassicalType::Bit); + source + .store(target, ClassicalExpr::bit_literal(true)) + .unwrap(); + for bindings in [None, Some(HashMap::new())] { + let bound = source.assign_parameters(&bindings).unwrap(); + bound.validate().unwrap(); + assert_ne!(bound.id(), source.id()); + assert_eq!(bound.classical_vars(), source.classical_vars()); + let execution = StabilizerState::run_circuit(&bound).unwrap(); + let Instruction::ClassicalData(ClassicalDataOp::Store { + target: bound_target, + .. + }) = bound.operations()[0].instruction + else { + panic!("expected Store"); + }; + assert_eq!( + execution.classical.var(bound_target), + Some(&RuntimeValue::Bit(true)) + ); + assert!(bound.validate_classical_var(unused).is_err()); + assert!(execution.classical.var(target).is_none()); + } +} + +#[test] +fn test_assign_parameters_still_rejects_classical_control() { + let mut source = Circuit::new(1); + source + .if_(ClassicalExpr::bool_literal(true), |body| { + body.rx(Qubit::new(0), "theta") + }) + .unwrap(); + assert!(matches!( + source.assign_parameters(&None), + Err(CircuitError::InvalidOperation(_)) + )); +} + #[test] fn test_parameterized_unitary_appends_fixed_and_symbolic_params() { let mut circuit = Circuit::new(1); @@ -1359,8 +1556,6 @@ fn test_parameterized_unitary_validates_param_count() { #[test] fn test_decompose() { - use std::collections::HashMap; - let mut inner = Circuit::new(2); let q0 = Qubit::new(0); let q1 = Qubit::new(1); @@ -1447,6 +1642,247 @@ fn test_decompose() { } } +#[test] +fn test_decompose_global_phase_constant_and_empty_definitions() { + for (width, has_operations) in [(0, false), (1, false), (1, true), (2, true)] { + let mut inner = Circuit::new(width); + inner.set_global_phase(Parameter::from(0.37)); + if has_operations { + inner.x(Qubit::new(0)).unwrap(); + if width == 2 { + inner.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + } + } + let gate = inner.to_gate("Phased").unwrap(); + for repetitions in 0..=2 { + let mut outer = Circuit::new(2); + outer.set_global_phase(Parameter::from(0.12)); + let mut expected = Circuit::new(2); + expected.set_global_phase(Parameter::from(0.12 + repetitions as f64 * 0.37)); + for _ in 0..repetitions { + let targets = [Qubit::new(1), Qubit::new(0)]; + outer + .append(gate.clone(), targets[..width].to_vec(), [], None) + .unwrap(); + if has_operations { + expected.x(Qubit::new(1)).unwrap(); + if width == 2 { + expected.cx(Qubit::new(1), Qubit::new(0)).unwrap(); + } + } + } + let flat = outer.decompose().unwrap(); + assert!( + (flat.global_phase().evaluate(&None).unwrap() - (0.12 + repetitions as f64 * 0.37)) + .abs() + < 1e-12 + ); + let expected_matrix = circuit_to_matrix(&expected, None).unwrap(); + assert_matrix_approx_eq( + &circuit_to_matrix(&outer, None).unwrap(), + &expected_matrix, + 1e-10, + ); + assert_matrix_approx_eq( + &circuit_to_matrix(&flat, None).unwrap(), + &expected_matrix, + 1e-10, + ); + assert_matrix_approx_eq( + &circuit_to_matrix(&flat.decompose().unwrap(), None).unwrap(), + &expected_matrix, + 1e-10, + ); + assert_eq!(flat.operations().len(), expected.operations().len()); + assert_eq!(outer.global_phase().evaluate(&None).unwrap(), 0.12); + } + } +} + +#[test] +fn test_decompose_global_phase_only_symbols_and_explicit_signature() { + let mut inner = Circuit::new(1); + inner.set_global_phase(Parameter::symbol("theta") / 2.0); + let gate = CircuitGate::with_signature( + "PhaseOnly", + FrozenCircuit::new(inner), + ["unused".to_string(), "theta".to_string()], + ) + .unwrap(); + let mut outer = Circuit::new(1); + outer.set_global_phase(Parameter::symbol("phi") / 3.0); + outer + .circuit_gate( + gate, + vec![Qubit::new(0)], + [ + ParameterValue::Fixed(0.7), + ParameterValue::from(Parameter::symbol("x") * 2.0), + ], + ) + .unwrap(); + let flat = outer.decompose().unwrap(); + assert!(flat.operations().is_empty()); + assert_eq!( + flat.used_symbols().iter().cloned().collect::>(), + HashSet::from(["phi".to_string(), "x".to_string()]) + ); + for (x, phi) in [(0.37, -0.23), (-0.61, 0.44)] { + let bindings = Some(HashMap::from([("x", x), ("phi", phi)])); + let mut expected = Circuit::new(1); + expected.set_global_phase(Parameter::from(phi / 3.0 + x)); + let expected_matrix = circuit_to_matrix(&expected, None).unwrap(); + assert_matrix_approx_eq( + &circuit_to_matrix(&flat.assign_parameters(&bindings).unwrap(), None).unwrap(), + &expected_matrix, + 1e-10, + ); + assert_matrix_approx_eq( + &circuit_to_matrix( + &outer + .assign_parameters(&bindings) + .unwrap() + .decompose() + .unwrap(), + None, + ) + .unwrap(), + &expected_matrix, + 1e-10, + ); + } +} + +#[test] +fn test_decompose_global_phase_nested_symbolic_and_inverse() { + let a = Parameter::symbol("a"); + let b = Parameter::symbol("b"); + let mut inner = Circuit::from_qubits(vec![Qubit::new(7), Qubit::new(2)]).unwrap(); + inner.set_global_phase(a.clone() + b.clone() * 2.0); + inner.rx(Qubit::new(7), a.clone() - b.clone()).unwrap(); + inner.cx(Qubit::new(7), Qubit::new(2)).unwrap(); + let inner_gate = CircuitGate::with_signature( + "Inner", + FrozenCircuit::new(inner), + ["a".to_string(), "b".to_string()], + ) + .unwrap(); + let mut middle = Circuit::from_qubits(vec![Qubit::new(5), Qubit::new(1)]).unwrap(); + middle.set_global_phase(a.clone() / 2.0); + middle + .circuit_gate( + inner_gate, + vec![Qubit::new(5), Qubit::new(1)], + [ParameterValue::from(b), ParameterValue::from(a)], + ) + .unwrap(); + let middle_gate = CircuitGate::with_signature( + "Middle", + FrozenCircuit::new(middle), + ["a".to_string(), "b".to_string()], + ) + .unwrap(); + let x = Parameter::symbol("x"); + let mut outer = Circuit::new(2); + outer.set_global_phase(x.clone() / 3.0); + outer + .circuit_gate( + middle_gate, + vec![Qubit::new(1), Qubit::new(0)], + [ + ParameterValue::from(x + 1.0), + ParameterValue::from(Parameter::symbol("y")), + ], + ) + .unwrap(); + + for inverse in [false, true] { + let circuit = if inverse { + outer.inverse().unwrap() + } else { + outer.clone() + }; + let flat = circuit.decompose().unwrap(); + assert_eq!( + flat.used_symbols().iter().cloned().collect::>(), + HashSet::from(["x".to_string(), "y".to_string()]) + ); + let symbolic = circuit_to_symbolic_matrix(&flat, None).unwrap(); + for (x, y) in [(0.37, -0.23), (-0.61, 0.44)] { + let bindings = Some(HashMap::from([("x", x), ("y", y)])); + let mut expected = Circuit::new(2); + let expected_phase = x / 3.0 + (x + 1.0) / 2.0 + y + 2.0 * (x + 1.0); + expected.set_global_phase(Parameter::from(expected_phase)); + expected.rx(Qubit::new(1), y - (x + 1.0)).unwrap(); + expected.cx(Qubit::new(1), Qubit::new(0)).unwrap(); + if inverse { + expected = expected.inverse().unwrap(); + } + let expected_matrix = circuit_to_matrix(&expected, None).unwrap(); + assert!( + (flat.global_phase().evaluate(&bindings).unwrap() + - if inverse { + -expected_phase + } else { + expected_phase + }) + .abs() + < 1e-12 + ); + for candidate in [ + flat.assign_parameters(&bindings).unwrap(), + circuit + .assign_parameters(&bindings) + .unwrap() + .decompose() + .unwrap(), + circuit.assign_parameters(&bindings).unwrap(), + ] { + assert_matrix_approx_eq( + &circuit_to_matrix(&candidate, None).unwrap(), + &expected_matrix, + 1e-10, + ); + } + assert_matrix_approx_eq( + &evaluate_symbolic_matrix(&symbolic, &bindings).unwrap(), + &expected_matrix, + 1e-10, + ); + } + } +} + +#[test] +fn test_decompose_global_phase_rejects_invalid_constants() { + let mut inner = Circuit::new(1); + inner.set_global_phase(Parameter::symbol("theta").ln()); + let mut outer = Circuit::new(1); + outer + .append( + inner.to_gate("LogPhase").unwrap(), + [Qubit::new(0)], + [ParameterValue::Fixed(-1.0)], + None, + ) + .unwrap(); + assert!(outer.decompose().is_err()); + + let mut inner = Circuit::new(1); + inner.set_global_phase(Parameter::from(1e308)); + let mut outer = Circuit::new(1); + outer.set_global_phase(Parameter::from(1e308)); + outer + .append( + inner.to_gate("LargePhase").unwrap(), + [Qubit::new(0)], + [], + None, + ) + .unwrap(); + assert!(outer.decompose().is_err()); +} + #[test] fn test_decompose_nested() { let mut l1 = Circuit::new(1); @@ -1790,6 +2226,193 @@ fn test_control_op_constructor_error_rolls_back_captured_state() { assert!(circuit.classical_values().is_empty()); } +fn control_rollback_source() -> Circuit { + let mut source = Circuit::from_qubits(vec![Qubit::new(7)]).unwrap(); + source.rx(Qubit::new(7), "theta").unwrap(); + source.set_global_phase(Parameter::symbol("phase")); + let value = source.measure(Qubit::new(7)).unwrap(); + let var = source.var(ClassicalType::Bit); + source.store(var, value.expr()).unwrap(); + source +} + +fn control_rollback_error() -> Result<(), CircuitError> { + Err(CircuitError::InvalidOperation("stop".into())) +} + +fn assert_failed_control_build_restores_state( + circuit: &mut Circuit, + build: impl FnOnce(&mut Circuit) -> Result<(), CircuitError>, +) { + let id = circuit.id(); + let qubits = circuit.qubits(); + let parameters: Vec<_> = circuit.parameters().iter().cloned().collect(); + let symbols: Vec<_> = circuit.symbols().iter().cloned().collect(); + let data = circuit.data.clone(); + let vars = circuit.classical_vars.clone(); + let values = circuit.classical_values.clone(); + let scopes = circuit.control_scope_stack.clone(); + let phase = circuit.global_phase(); + let phase_param = circuit.global_phase_param().clone(); + + assert!(build(circuit).is_err()); + + // Exercise the accessor that panicked when rollback left a dangling index. + assert_eq!(circuit.global_phase(), phase); + assert_eq!(circuit.global_phase_param(), &phase_param); + assert_eq!(circuit.id(), id); + assert_eq!(circuit.qubits(), qubits); + assert_eq!( + circuit.parameters().iter().cloned().collect::>(), + parameters + ); + assert_eq!( + circuit.symbols().iter().cloned().collect::>(), + symbols + ); + assert_eq!(circuit.data, data); + assert_eq!(circuit.classical_vars, vars); + assert_eq!(circuit.classical_values, values); + assert_eq!(circuit.control_scope_stack, scopes); +} + +#[test] +fn test_control_rollback_callback_failure_restores_composed_state_and_existing_handles() { + let source = control_rollback_source(); + for phase in [ + Parameter::from(0.0), + Parameter::from(0.375), + Parameter::symbol("old_phase"), + ] { + let mut circuit = + Circuit::from_qubits(vec![Qubit::new(9), Qubit::new(2), Qubit::new(5)]).unwrap(); + circuit.set_global_phase(phase); + circuit.rx(Qubit::new(2), "old_theta").unwrap(); + let measured = circuit.measure(Qubit::new(9)).unwrap(); + let var = circuit.var(ClassicalType::Bit); + circuit.store(var, measured.expr()).unwrap(); + + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + circuit.if_(ClassicalExpr::bool_literal(true), |body| { + body.compose(&source, None).unwrap(); + control_rollback_error() + }) + }); + + circuit.validate_classical_var(var).unwrap(); + circuit.store(var, measured.expr()).unwrap(); + circuit.validate().unwrap(); + } +} + +#[test] +fn test_control_rollback_callback_failure_restores_direct_qubit_and_phase_changes() { + let mut circuit = Circuit::new(1); + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + circuit.if_(ClassicalExpr::bool_literal(true), |body| { + body.add_qubits(vec![Qubit::new(7)]).unwrap(); + control_rollback_error() + }) + }); + for phase in [Parameter::from(0.75), Parameter::symbol("discarded")] { + circuit.set_global_phase(0.25.into()); + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + circuit.if_(ClassicalExpr::bool_literal(true), |body| { + body.set_global_phase(phase); + control_rollback_error() + }) + }); + } +} + +#[test] +fn test_control_rollback_outer_failure_restores_state_after_successful_bodies() { + let source = control_rollback_source(); + for failure in ["else", "switch-case", "constructor", "nested-loop"] { + let mut circuit = Circuit::new(1); + assert_failed_control_build_restores_state(&mut circuit, |circuit| match failure { + "else" => circuit.if_else( + ClassicalExpr::bool_literal(true), + |body| { + body.compose(&source, None).unwrap(); + Ok(()) + }, + |_| control_rollback_error(), + ), + "switch-case" => circuit.switch(ClassicalExpr::uint_literal(2, 0).unwrap(), |cases| { + cases + .value(0, |body| { + body.compose(&source, None).unwrap(); + Ok(()) + }) + .unwrap(); + cases.value(1, |_| control_rollback_error()) + }), + "constructor" => circuit.if_(ClassicalExpr::bit_literal(true), |body| { + body.compose(&source, None).unwrap(); + Ok(()) + }), + "nested-loop" => circuit.while_(ClassicalExpr::bool_literal(true), |body| { + body.if_(ClassicalExpr::bool_literal(true), |inner| { + inner.compose(&source, None).unwrap(); + Ok(()) + }) + .unwrap(); + control_rollback_error() + }), + _ => unreachable!(), + }); + circuit.validate().unwrap(); + } +} + +#[test] +fn test_control_rollback_external_transaction_rollback_restores_state_before_and_after_capture() { + let source = control_rollback_source(); + for capture in [false, true] { + let mut circuit = Circuit::new(1); + circuit.set_global_phase(Parameter::symbol("old_phase")); + assert_failed_control_build_restores_state(&mut circuit, |circuit| { + let transaction = circuit.begin_control_body_transaction(); + circuit.enter_external_control_body(&transaction, ExternalControlScope::Loop); + circuit.compose(&source, None).unwrap(); + if capture { + let body = circuit.finish_external_control_body(&transaction); + assert_eq!(body.operations().len(), source.operations().len()); + } + circuit.rollback_control_body_transaction(transaction); + control_rollback_error() + }); + circuit.validate().unwrap(); + } +} + +#[test] +fn test_control_rollback_nested_rollback_preserves_enclosing_loop_state() { + let source = control_rollback_source(); + let mut circuit = Circuit::new(1); + circuit + .while_(ClassicalExpr::bool_literal(true), |body| { + body.add_qubits(vec![Qubit::new(3)])?; + body.rx(Qubit::new(3), "outer_theta")?; + body.set_global_phase(Parameter::symbol("outer_phase")); + assert_failed_control_build_restores_state(body, |body| { + body.if_(ClassicalExpr::bool_literal(true), |inner| { + inner.compose(&source, None).unwrap(); + control_rollback_error() + }) + }); + body.continue_loop() + }) + .unwrap(); + + assert_eq!(circuit.qubits(), vec![Qubit::new(0), Qubit::new(3)]); + assert_eq!(circuit.global_phase(), Parameter::symbol("outer_phase")); + assert!(circuit.control_scope_stack.is_empty()); + assert!(circuit.continue_loop().is_err()); + circuit.validate().unwrap(); +} + #[test] fn test_decompose_rejects_classical_control() { let mut circuit = Circuit::new(2); @@ -1828,6 +2451,228 @@ fn test_decompose_remaps_classical_data_identity() { } } +#[test] +fn compose_rejects_duplicate_targets_without_changing_either_circuit() { + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + // The mapping is a wire embedding, even for idle or separately used wires. + for kind in 0..3 { + for width in [1, 2] { + let mut destination = Circuit::new(width); + destination.rx(q0, "existing").unwrap(); + destination.set_global_phase(Parameter::symbol("phase")); + destination.var(ClassicalType::Bit); + destination.measure(q0).unwrap(); + let mut source = Circuit::new(2); + match kind { + 0 => source.cx(q0, q1).unwrap(), + 1 => { + source.x(q0).unwrap(); + source.h(q1).unwrap(); + } + _ => {} + } + source.rx(q0, "new_parameter").unwrap(); + source.var(ClassicalType::Bit); + if kind != 2 { + source.measure(q1).unwrap(); + } + let before = format!("{destination:?}"); + let source_before = format!("{source:?}"); + + assert!(matches!( + destination.compose(&source, Some(&[q0, q0])), + Err(CircuitError::DuplicateQubits) + )); + assert_eq!(format!("{destination:?}"), before); + assert_eq!(format!("{source:?}"), source_before); + } + } +} + +#[test] +fn compose_errors_leave_all_destination_state_unchanged() { + let q0 = Qubit::new(0); + let q7 = Qubit::new(7); + // Inject malformed storage IR to exercise errors after mapping/parameter preparation. + for failure in [ + "parameter", + "qubit", + "classical", + "phase", + "destination_phase", + ] { + for explicit in [false, true] { + let mut destination = Circuit::new(1); + destination.rx(q0, "existing").unwrap(); + destination.set_global_phase(Parameter::from(0.25)); + let retained_var = destination.var(ClassicalType::Bit); + let retained_value = destination.measure(q0).unwrap(); + let mut source = Circuit::from_qubits(vec![q7]).unwrap(); + source.rx(q7, "new_parameter").unwrap(); + source.measure(q7).unwrap(); + match failure { + "parameter" => { + Arc::make_mut(&mut source.data)[0].params[0] = CircuitParam::Index(u32::MAX); + } + "qubit" => { + Arc::make_mut(&mut source.data)[0].qubits[0] = Qubit::new(99); + } + "classical" => { + Arc::make_mut(&mut source.data)[1].instruction = + Instruction::ClassicalData(ClassicalDataOp::MeasureBit { + result: ClassicalValue::new(destination.id(), 0, ClassicalType::Bit), + }); + } + "phase" => source.global_phase = CircuitParam::Index(u32::MAX), + "destination_phase" => { + // Merging the source parameter must not make a bad old index valid. + destination.global_phase = + CircuitParam::Index(destination.parameters.len() as u32); + } + _ => unreachable!(), + } + let before = format!("{destination:?}"); + let source_before = format!("{source:?}"); + let mapping = [q0]; + assert!( + destination + .compose(&source, explicit.then_some(&mapping[..])) + .is_err(), + "{failure}" + ); + assert_eq!(format!("{destination:?}"), before, "{failure}"); + assert_eq!(format!("{source:?}"), source_before); + destination.validate_classical_var(retained_var).unwrap(); + destination + .store(retained_var, retained_value.expr()) + .unwrap(); + } + } +} + +#[test] +fn compose_sparse_permutation_preserves_unitary_parameters_and_phase() { + let [q9, q2, q5] = [9, 2, 5].map(Qubit::new); + let [q8, q1] = [8, 1].map(Qubit::new); + for symbolic_left in [false, true] { + for symbolic_right in [false, true] { + let left = if symbolic_left { + Parameter::symbol("left") + } else { + Parameter::from(0.25) + }; + let right = if symbolic_right { + Parameter::symbol("right") + } else { + Parameter::from(-0.75) + }; + let mut destination = Circuit::from_qubits(vec![q9, q2, q5]).unwrap(); + destination.h(q9).unwrap(); + destination.cx(q9, q5).unwrap(); + destination.set_global_phase(left.clone()); + let id = destination.id(); + let mut definition = Circuit::new(2); + definition.ry(Qubit::new(0), "theta").unwrap(); + definition.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + let gate = definition.to_gate("rotation_pair").unwrap(); + let mut source = Circuit::from_qubits(vec![q8, q1]).unwrap(); + source + .append( + gate.clone(), + [q8, q1], + [Parameter::symbol("theta").into()], + Some("pair"), + ) + .unwrap(); + source.rz(q1, "theta").unwrap(); + source.set_global_phase(right.clone()); + let source_before = format!("{source:?}"); + + destination.compose(&source, Some(&[q5, q2])).unwrap(); + + let mut expected = Circuit::from_qubits(vec![q9, q2, q5]).unwrap(); + expected.h(q9).unwrap(); + expected.cx(q9, q5).unwrap(); + expected + .append( + gate, + [q5, q2], + [Parameter::symbol("theta").into()], + Some("pair"), + ) + .unwrap(); + expected.rz(q2, "theta").unwrap(); + expected.set_global_phase(left + right); + let bindings = Some(HashMap::from([ + ("theta", 0.731), + ("left", -0.4), + ("right", 1.2), + ])); + assert_matrix_approx_eq( + &destination + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + &expected + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + 1e-12, + ); + assert_eq!(destination.id(), id); + assert_eq!(destination.qubits(), vec![q9, q2, q5]); + assert_eq!(destination.operations()[2].label.as_deref(), Some("pair")); + assert_eq!(format!("{source:?}"), source_before); + } + } +} + +#[test] +fn compose_preserves_existing_handles_inside_control_builder() { + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + let mut destination = Circuit::new(2); + let id = destination.id(); + let retained_var = destination.var(ClassicalType::Bit); + let retained_value = destination.measure(q0).unwrap(); + let mut source = Circuit::new(2); + let measured = source.measure(q0).unwrap(); + source + .if_( + ClassicalExpr::bit_to_bool(measured.expr()).unwrap(), + |body| body.cx(q0, q1), + ) + .unwrap(); + + destination + .while_(ClassicalExpr::bool_literal(true), |body| { + body.compose(&source, Some(&[q1, q0]))?; + body.store(retained_var, retained_value.expr())?; + body.break_loop() + }) + .unwrap(); + assert_eq!(destination.id(), id); + destination + .store(retained_var, retained_value.expr()) + .unwrap(); + destination.validate().unwrap(); + let Instruction::ClassicalControl(ClassicalControlOp::While(op)) = + &destination.operations()[1].instruction + else { + panic!("expected while") + }; + assert_eq!(op.body().operations()[0].qubits.as_slice(), &[q1]); + let Instruction::ClassicalControl(ClassicalControlOp::If(op)) = + &op.body().operations()[1].instruction + else { + panic!("expected if") + }; + assert_eq!(op.then_body().operations()[0].qubits.as_slice(), &[q1, q0]); +} + #[test] fn test_compose_basic_with_mapping() { // Create qc1 with qubits 1, 3, 5 @@ -1977,6 +2822,97 @@ fn test_compose_with_parameters() { assert!(qc1.symbols().contains("phi")); } +#[test] +fn compose_interns_phase_sum_in_existing_or_new_parameters() { + let q0 = Qubit::new(0); + for location in ["destination", "source", "phase_only"] { + let phi = Parameter::symbol("phi"); + let psi = Parameter::symbol("psi"); + let sum = phi.clone() + psi.clone(); + let mut destination = Circuit::new(1); + destination.rx(q0, "existing").unwrap(); + destination.set_global_phase(phi); + if location == "destination" { + destination.rz(q0, sum.clone()).unwrap(); + } + let id = destination.id(); + let retained_var = destination.var(ClassicalType::Bit); + let retained_value = destination.measure(q0).unwrap(); + let mut source = Circuit::new(1); + source.rx(q0, "existing").unwrap(); + source.ry(q0, "new").unwrap(); + source.rz(q0, "new").unwrap(); + if location == "source" { + source.rx(q0, sum.clone()).unwrap(); + } + source.set_global_phase(psi); + let source_before = format!("{source:?}"); + let operation_base = destination.data.len(); + let mut expected_parameters = destination.parameters.clone(); + expected_parameters.extend(source.parameters.iter().cloned()); + expected_parameters.insert(sum.clone()); + + destination.compose(&source, None).unwrap(); + + assert_eq!( + destination.parameters.iter().collect::>(), + expected_parameters.iter().collect::>() + ); + assert_eq!(destination.global_phase(), sum); + assert_eq!( + destination.global_phase_param(), + &CircuitParam::Index(expected_parameters.get_index_of(&sum).unwrap() as u32) + ); + assert_eq!(destination.id(), id); + assert_eq!(format!("{source:?}"), source_before); + for (original, remapped) in source.data.iter().zip(&destination.data[operation_base..]) { + for (source_param, mapped_param) in original.params.iter().zip(&remapped.params) { + assert_eq!( + source.resolve_parameter(source_param).unwrap(), + destination.resolve_parameter(mapped_param).unwrap() + ); + } + } + assert_eq!( + destination.symbols.iter().cloned().collect::>(), + HashSet::from(["existing", "new", "phi", "psi"].map(String::from)) + ); + destination + .store(retained_var, retained_value.expr()) + .unwrap(); + destination.validate().unwrap(); + } +} + +#[test] +fn compose_repeated_parameters_preserve_indices_and_insertion_order() { + let q0 = Qubit::new(0); + let mut destination = Circuit::new(1); + let mut expected = Circuit::new(1); + for i in 0..128 { + let theta = Parameter::symbol(&format!("theta_{i}")); + let mut source = Circuit::new(1); + source.rx(q0, theta.clone()).unwrap(); + source.ry(q0, "shared").unwrap(); + destination.compose(&source, None).unwrap(); + expected.rx(q0, theta).unwrap(); + expected.ry(q0, "shared").unwrap(); + } + + assert_eq!(destination, expected); + assert_eq!( + destination.parameters.iter().collect::>(), + expected.parameters.iter().collect::>() + ); + assert_eq!( + destination.symbols.iter().collect::>(), + expected.symbols.iter().collect::>() + ); + for (actual, expected) in destination.operations().iter().zip(expected.operations()) { + assert_eq!(actual.params, expected.params); + } +} + #[test] fn test_compose_preserves_operation_order() { // qc1: Bell state preparation diff --git a/crates/cqlib-core/src/circuit/circuit_to_matrix.rs b/crates/cqlib-core/src/circuit/circuit_to_matrix.rs index ed6a0694..f72835fb 100644 --- a/crates/cqlib-core/src/circuit/circuit_to_matrix.rs +++ b/crates/cqlib-core/src/circuit/circuit_to_matrix.rs @@ -26,7 +26,7 @@ //! //! ## Memory Layout & Convention //! -//! - **State Vector Ordering**: Little-Endian (similar to Qiskit). Qubit 0 corresponds to the Least Significant Bit (LSB). +//! - **State Vector Ordering**: Little-Endian. Qubit 0 corresponds to the Least Significant Bit (LSB). //! State $|q_{n-1} \dots q_1 q_0\rangle$. //! - **Parallelization**: Large matrix multiplications (large state spaces) are automatically parallelized using `rayon`. @@ -123,7 +123,7 @@ pub fn circuit_to_matrix( // Map logical qubit index to physical bit position (0 to N-1). // Little-Endian mapping: first qubit in target_order corresponds to LSB (bit 0) // q0 -> bit 0, q1 -> bit 1, ... - // This matches Qiskit's convention. + // Qubit 0 occupies the least significant bit. let qubit_bit_map: HashMap = target_order .iter() .enumerate() @@ -198,23 +198,11 @@ pub fn circuit_to_matrix( } } Instruction::CircuitGate(circuit_gate) => { - let symbols = circuit_gate.signature_params(); - let expected = symbols.len(); - let actual = params.len(); - if actual != expected { - return Err(CircuitError::ParameterCountMismatch { expected, actual }); - } - let mut bindings = HashMap::new(); - for (sym, val) in symbols.iter().zip(params.iter()) { - bindings.insert(sym.as_str(), *val); - } - let sub_circuit = circuit_gate - .circuit - .circuit - .assign_parameters(&Some(bindings)) - .map_err(|_| CircuitError::SymbolicParameterError)?; - let sub_matrix = circuit_to_matrix(&sub_circuit, None)?; - apply_gate_to_matrix(&mut matrix, &sub_matrix, &bits)?; + let gate_matrix = circuit_gate.matrix_for_params(params.as_slice())?; + // Gate-local matrices put the first positional argument at MSB; + // the full circuit uses an LSB-first basis, as for standard gates. + let reversed_bits: SmallVec<[usize; 3]> = bits.iter().copied().rev().collect(); + apply_gate_to_matrix(&mut matrix, &gate_matrix, &reversed_bits)?; } Instruction::ClassicalControl(_) => { return Err(CircuitError::InvalidOperation( diff --git a/crates/cqlib-core/src/circuit/circuit_to_matrix_test.rs b/crates/cqlib-core/src/circuit/circuit_to_matrix_test.rs index 86754c4d..5f223d51 100644 --- a/crates/cqlib-core/src/circuit/circuit_to_matrix_test.rs +++ b/crates/cqlib-core/src/circuit/circuit_to_matrix_test.rs @@ -419,6 +419,76 @@ fn test_unitary_gate_two_qubit() { assert!((matrix[[1, 2]] - c(1.0, 0.0)).norm() < 1e-10); } +#[test] +fn test_circuit_gate_storage_order_mapping() { + for order in [[7, 2], [1, 0], [2, 7], [0, 1]] { + let mut inner = Circuit::from_qubits(order.map(Qubit::new).to_vec()).unwrap(); + inner.x(Qubit::new(order[0])).unwrap(); + let gate = inner.to_gate("StoredOrderX").unwrap(); + for targets in [[0, 1], [1, 0]] { + let mut circuit = Circuit::new(2); + circuit + .append(gate.clone(), targets.map(Qubit::new), [], None) + .unwrap(); + let mut expected = Circuit::new(2); + expected.x(Qubit::new(targets[0])).unwrap(); + let matrix = circuit_to_matrix(&circuit, None).unwrap(); + let expected = circuit_to_matrix(&expected, None).unwrap(); + assert_matrix_approx_eq(&matrix, &expected, 1e-10); + assert_eq!(matrix[[1 << targets[0], 0]], c(1.0, 0.0)); + assert_matrix_approx_eq( + &matrix, + &circuit_to_matrix(&circuit.decompose().unwrap(), None).unwrap(), + 1e-10, + ); + } + } +} + +#[test] +fn test_circuit_gate_storage_order_three_qubit_permutations() { + let permutations = [ + [0, 1, 2], + [0, 2, 1], + [1, 0, 2], + [1, 2, 0], + [2, 0, 1], + [2, 1, 0], + ]; + let inner_ids = [2, 7, 11]; + let outer_ids = [4, 9, 15]; + for permutation in permutations { + let order = permutation.map(|i| Qubit::new(inner_ids[i])); + let mut inner = Circuit::from_qubits(order.to_vec()).unwrap(); + inner.x(order[0]).unwrap(); + inner.ry(order[1], 0.37).unwrap(); + inner.cx(order[0], order[2]).unwrap(); + let gate = inner.to_gate("Permuted").unwrap(); + for target_permutation in permutations { + let targets = target_permutation.map(|i| Qubit::new(outer_ids[i])); + let mut circuit = Circuit::from_qubits(outer_ids.map(Qubit::new).to_vec()).unwrap(); + circuit.append(gate.clone(), targets, [], None).unwrap(); + let mut expected = Circuit::from_qubits(outer_ids.map(Qubit::new).to_vec()).unwrap(); + expected.x(targets[0]).unwrap(); + expected.ry(targets[1], 0.37).unwrap(); + expected.cx(targets[0], targets[2]).unwrap(); + for output_order in [None, Some([15, 4, 9].as_slice())] { + let matrix = circuit_to_matrix(&circuit, output_order).unwrap(); + assert_matrix_approx_eq( + &matrix, + &circuit_to_matrix(&expected, output_order).unwrap(), + 1e-10, + ); + assert_matrix_approx_eq( + &matrix, + &circuit_to_matrix(&circuit.decompose().unwrap(), output_order).unwrap(), + 1e-10, + ); + } + } + } +} + #[test] fn test_circuit_gate_bell_state() { // Create a Bell state preparation circuit as a gate @@ -866,6 +936,74 @@ fn test_global_phase_is_included_for_empty_circuit() { assert_matrix_approx_eq(&matrix, &expected, 1e-10); } +#[test] +fn test_gphase_markers_accumulate_with_circuit_global_phase() { + for num_qubits in [0, 1, 3] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut circuit = Circuit::new(num_qubits); + if num_qubits > 0 { + circuit.h(Qubit::new(0)).unwrap(); + } + let baseline = circuit_to_matrix(&circuit, None).unwrap(); + for phase in [theta, -0.21] { + circuit + .append( + Instruction::Standard(StandardGate::GPhase), + [] as [Qubit; 0], + [phase.into()], + None, + ) + .unwrap(); + } + circuit.set_global_phase(Parameter::from(0.17)); + let expected = baseline * Complex64::from_polar(1.0, theta - 0.21 + 0.17); + let actual = circuit_to_matrix(&circuit, None).unwrap(); + assert_matrix_approx_eq(&actual, &expected, 1e-12); + } + } +} + +#[test] +fn test_gphase_controlled_embedding_with_spectator_and_custom_order() { + for controls in [vec![], vec![2usize], vec![2, 0]] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut circuit = Circuit::new(3); + circuit.h(Qubit::new(1)).unwrap(); + circuit + .multi_control( + StandardGate::GPhase, + controls.iter().map(|&q| Qubit::new(q as u32)), + [] as [Qubit; 0], + [theta.into()], + ) + .unwrap(); + for order in [[0, 1, 2], [2, 0, 1]] { + let spectator_bit = order.iter().position(|&q| q == 1).unwrap(); + let mask = controls.iter().fold(0, |mask, control| { + mask | (1 << order.iter().position(|q| q == control).unwrap()) + }); + let mut expected = Array2::zeros((8, 8)); + for row in 0..8 { + for col in 0..8 { + if (row ^ col) & !(1 << spectator_bit) == 0 { + let sign = if row & col & (1 << spectator_bit) != 0 { + -1.0 + } else { + 1.0 + }; + let phase = if row & mask == mask { theta } else { 0.0 }; + expected[[row, col]] = + Complex64::from_polar(1.0, phase) * sign / SQRT_2; + } + } + } + let actual = circuit_to_matrix(&circuit, Some(&order)).unwrap(); + assert_matrix_approx_eq(&actual, &expected, 1e-12); + } + } + } +} + #[test] fn test_global_phase_is_included_with_gate() { let mut circuit = Circuit::new(1); diff --git a/crates/cqlib-core/src/circuit/gate/circuit_gate.rs b/crates/cqlib-core/src/circuit/gate/circuit_gate.rs index 7cbeca3d..5eaf87a9 100644 --- a/crates/cqlib-core/src/circuit/gate/circuit_gate.rs +++ b/crates/cqlib-core/src/circuit/gate/circuit_gate.rs @@ -16,10 +16,15 @@ //! quantum circuits to be used as reusable gate components within other circuits. //! This enables hierarchical circuit construction and custom composite gates. +use crate::circuit::Qubit; use crate::circuit::circuit_impl::Circuit; +use crate::circuit::circuit_to_matrix; use crate::circuit::error::CircuitError; use crate::circuit::symbolic_matrix::{SymbolicMatrix, circuit_to_symbolic_matrix}; use indexmap::IndexSet; +use ndarray::Array2; +use num_complex::Complex64; +use std::collections::HashMap; use std::sync::{Arc, OnceLock}; /// An immutable, frozen circuit for use in gate definitions. @@ -46,6 +51,7 @@ pub struct FrozenCircuit { pub(crate) circuit: Circuit, used_symbols: Arc>, symbolic_matrix_cache: Arc>>, + storage_order_symbolic_matrix_cache: Arc>>, } impl FrozenCircuit { @@ -67,6 +73,7 @@ impl FrozenCircuit { circuit, used_symbols, symbolic_matrix_cache: Arc::new(OnceLock::new()), + storage_order_symbolic_matrix_cache: Arc::new(OnceLock::new()), } } @@ -95,6 +102,16 @@ impl FrozenCircuit { &self.used_symbols } + /// The default matrix order, from least to most significant bit. + /// + /// Circuit-backed UnitaryGate definitions map this order positionally to + /// the caller's qubits. CircuitGate instead uses circuit storage order. + pub(crate) fn qubits_in_numeric_order(&self) -> Vec { + let mut qubits = self.circuit.qubits(); + qubits.sort_unstable(); + qubits + } + /// Returns the cached symbolic matrix for this frozen circuit. /// /// The matrix is computed in the circuit's default qubit order on the @@ -105,10 +122,32 @@ impl FrozenCircuit { return Ok(matrix.clone()); } - let matrix = Arc::new(circuit_to_symbolic_matrix(&self.circuit, None)?); + let order: Vec = self + .qubits_in_numeric_order() + .iter() + .map(|q| q.index()) + .collect(); + let matrix = Arc::new(circuit_to_symbolic_matrix(&self.circuit, Some(&order))?); let _ = self.symbolic_matrix_cache.set(matrix.clone()); Ok(self.symbolic_matrix_cache.get().cloned().unwrap_or(matrix)) } + + /// CircuitGate's positional basis is distinct from the numeric-sorted + /// default used by the public FrozenCircuit matrix and UnitaryGate. + fn symbolic_matrix_in_storage_order(&self) -> Result, CircuitError> { + if let Some(matrix) = self.storage_order_symbolic_matrix_cache.get() { + return Ok(matrix.clone()); + } + + let order: Vec = self.circuit.qubits().iter().map(|q| q.index()).collect(); + let matrix = Arc::new(circuit_to_symbolic_matrix(&self.circuit, Some(&order))?); + let _ = self.storage_order_symbolic_matrix_cache.set(matrix.clone()); + Ok(self + .storage_order_symbolic_matrix_cache + .get() + .cloned() + .unwrap_or(matrix)) + } } impl PartialEq for FrozenCircuit { @@ -331,6 +370,40 @@ impl CircuitGate { self.num_params } + /// Resolves a numeric gate-local matrix, with the first positional + /// argument as the most-significant bit, like a standard gate matrix. + /// This differs from `symbolic_matrix`'s storage-order, little-endian basis. + pub(crate) fn matrix_for_params( + &self, + params: &[f64], + ) -> Result, CircuitError> { + if params.len() != self.signature_params.len() { + return Err(CircuitError::ParameterCountMismatch { + expected: self.signature_params.len(), + actual: params.len(), + }); + } + for (index, &value) in params.iter().enumerate() { + if !value.is_finite() { + return Err(CircuitError::InvalidParameterValue(index, value)); + } + } + let bindings: HashMap<&str, f64> = self + .signature_params + .iter() + .map(String::as_str) + .zip(params.iter().copied()) + .collect(); + let assigned = self + .circuit + .circuit + .assign_parameters(&Some(bindings)) + .map_err(|_| CircuitError::SymbolicParameterError)?; + // circuit_to_matrix takes LSB-first ordering; gate arguments are MSB-first. + let order: Vec = assigned.qubits().iter().rev().map(|q| q.index()).collect(); + circuit_to_matrix(&assigned, Some(&order)) + } + /// Returns a clone of the internal frozen circuit. /// /// # Examples @@ -350,9 +423,12 @@ impl CircuitGate { self.circuit.clone() } - /// Returns the cached symbolic matrix for this gate's frozen circuit. + /// Returns the cached symbolic matrix in this gate's positional basis. + /// + /// The first qubit in the inner circuit's storage order is the + /// least-significant matrix bit, matching the first application argument. pub fn symbolic_matrix(&self) -> Result, CircuitError> { - self.circuit.symbolic_matrix() + self.circuit.symbolic_matrix_in_storage_order() } /// Returns the name of this circuit gate. @@ -412,6 +488,82 @@ mod tests { use super::*; use crate::circuit::{Circuit, Parameter, Qubit}; + #[test] + fn numeric_matrix_binds_declared_signature_and_global_phase_without_mutation() { + let mut circuit = Circuit::from_qubits(vec![Qubit::new(7)]).unwrap(); + let theta = Parameter::symbol("theta"); + let phi = Parameter::symbol("phi"); + circuit.rx(Qubit::new(7), theta.clone()).unwrap(); + circuit.rz(Qubit::new(7), phi.clone()).unwrap(); + circuit.set_global_phase(theta + phi / Parameter::from(2.0)); + let gate = CircuitGate::with_signature( + "declared", + FrozenCircuit::new(circuit), + ["unused".to_string(), "phi".to_string(), "theta".to_string()], + ) + .unwrap(); + let original = gate.clone(); + for (theta, phi) in [(0.37_f64, -0.21_f64), (-0.61, 0.42), (0.37, -0.21)] { + let matrix = gate.matrix_for_params(&[12.0, phi, theta]).unwrap(); + for row in 0..2 { + let phase = theta + phi / 2.0 + if row == 0 { -phi / 2.0 } else { phi / 2.0 }; + for col in 0..2 { + let rx = if row == col { + Complex64::new((theta / 2.0).cos(), 0.0) + } else { + Complex64::new(0.0, -(theta / 2.0).sin()) + }; + assert!( + (matrix[[row, col]] - Complex64::from_polar(1.0, phase) * rx).norm() + < 1e-12 + ); + } + } + assert_eq!(gate, original); + assert_eq!(gate.used_symbols().len(), 2); + } + } + + #[test] + fn numeric_matrix_rejects_invalid_arguments_and_nonunitary_definitions() { + let gate = CircuitGate::with_signature( + "unused", + FrozenCircuit::new(Circuit::new(1)), + ["unused".to_string()], + ) + .unwrap(); + for params in [vec![], vec![0.1, 0.2]] { + assert!(matches!( + gate.matrix_for_params(¶ms), + Err(CircuitError::ParameterCountMismatch { expected: 1, .. }) + )); + } + for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(matches!( + gate.matrix_for_params(&[value]), + Err(CircuitError::InvalidParameterValue(0, _)) + )); + } + for directive in [ + crate::circuit::Directive::Measure, + crate::circuit::Directive::Reset, + ] { + let mut body = Circuit::new(1); + body.append( + crate::circuit::Instruction::Directive(directive), + [Qubit::new(0)], + [], + None, + ) + .unwrap(); + let gate = CircuitGate::new("nonunitary", FrozenCircuit::new(body)).unwrap(); + assert!(matches!( + gate.matrix_for_params(&[]), + Err(CircuitError::NoMatrixRepresentation) + )); + } + } + #[test] fn signature_params_are_distinct_from_used_symbols() { let mut circuit = Circuit::new(1); diff --git a/crates/cqlib-core/src/circuit/gate/gate_matrix.rs b/crates/cqlib-core/src/circuit/gate/gate_matrix.rs index f4792fc8..5477911f 100644 --- a/crates/cqlib-core/src/circuit/gate/gate_matrix.rs +++ b/crates/cqlib-core/src/circuit/gate/gate_matrix.rs @@ -581,17 +581,14 @@ pub fn phase_gate(lambda: f64) -> Array2> { array![[ONE, ZERO], [ZERO, exp_i_lambda]] } -/// Returns a global phase gate. +/// Returns the 1×1 matrix of a zero-qubit global phase gate. /// -/// This applies a global phase factor to the quantum state, physically equivalent to identity -/// but useful for mathematical consistency in simulations. +/// When embedded in a circuit, this scalar multiplies every state amplitude +/// by the same phase factor without requiring a target qubit. /// /// Defined as: /// ```text -/// [ -/// [exp(i*theta), 0 ], -/// [ 0, exp(i*theta)] -/// ] +/// [[exp(i*theta)]] /// ``` /// /// # Arguments @@ -601,7 +598,7 @@ pub fn phase_gate(lambda: f64) -> Array2> { pub fn global_phase_gate(theta: f64) -> Array2> { let (sin_val, cos_val) = theta.sin_cos(); let exp_i_theta = Complex::new(cos_val, sin_val); - array![[exp_i_theta, ZERO], [ZERO, exp_i_theta]] + array![[exp_i_theta]] } /// Returns the general single-qubit unitary gate (U3). diff --git a/crates/cqlib-core/src/circuit/gate/gate_matrix_test.rs b/crates/cqlib-core/src/circuit/gate/gate_matrix_test.rs index a6958d55..9444296e 100644 --- a/crates/cqlib-core/src/circuit/gate/gate_matrix_test.rs +++ b/crates/cqlib-core/src/circuit/gate/gate_matrix_test.rs @@ -11,6 +11,8 @@ // that they have been altered from the originals. use super::*; +use crate::circuit::Parameter; +use crate::circuit::gate::{MCGate, StandardGate}; use crate::circuit::test_utils::assert_is_unitary; use std::f64::consts::PI; @@ -27,6 +29,45 @@ fn assert_matrix_approx_eq(a: &Array2>, b: &Array2>) { } } +#[test] +fn test_gphase_scalar_matrix() { + for theta in [0.0, 0.37, -0.51, PI] { + let matrix = global_phase_gate(theta); + assert_eq!(matrix.dim(), (1, 1)); + assert!((matrix[[0, 0]] - Complex::from_polar(1.0, theta)).norm() < 1e-12); + assert_is_unitary(&matrix, 1e-12); + } +} + +#[test] +fn test_gphase_controlled_matrix_matches_metadata_and_inverse() { + assert_eq!(StandardGate::GPhase.num_qubits(), 0); + assert_eq!(StandardGate::GPhase.num_ctrl_qubits(), 0); + assert_eq!(StandardGate::GPhase.num_params(), 1); + for theta in [0.0, 0.37, -0.51, PI] { + for controls in 0..=2 { + let gate = MCGate::new(controls, StandardGate::GPhase); + assert_eq!(gate.num_qubits(), controls as usize); + let dim = 1 << gate.num_qubits(); + let matrix = gate.matrix(&[theta]).unwrap(); + let mut expected = Array2::eye(dim); + expected[[dim - 1, dim - 1]] = Complex::from_polar(1.0, theta); + crate::circuit::test_utils::assert_matrix_approx_eq(&matrix, &expected, 1e-12); + assert_is_unitary(&matrix, 1e-12); + + let (inverse, params) = gate.inverse(&[Parameter::from(theta)]).unwrap(); + let inverse_theta = params[0].evaluate(&None).unwrap(); + let inverse_matrix = inverse.matrix(&[inverse_theta]).unwrap(); + let expected_inverse = expected.t().mapv(|value| value.conj()); + crate::circuit::test_utils::assert_matrix_approx_eq( + &inverse_matrix, + &expected_inverse, + 1e-12, + ); + } + } +} + #[test] fn test_fixed_gates_unitary() { // Batch verify unitarity for all fixed gates diff --git a/crates/cqlib-core/src/circuit/gate/instruction.rs b/crates/cqlib-core/src/circuit/gate/instruction.rs index 4c33fbaa..7047f713 100644 --- a/crates/cqlib-core/src/circuit/gate/instruction.rs +++ b/crates/cqlib-core/src/circuit/gate/instruction.rs @@ -26,7 +26,7 @@ use crate::circuit::gate::circuit_gate::{CircuitGate, FrozenCircuit}; use crate::circuit::gate::directive::Directive; use crate::circuit::gate::standard_gate::StandardGate; use crate::circuit::gate::{ClassicalDataOp, MCGate, UnitaryGate, gate_matrix}; -use crate::circuit::{ClassicalControlOp, ClassicalValue, Parameter, circuit_to_matrix}; +use crate::circuit::{ClassicalControlOp, ClassicalValue, Parameter}; use alloc::borrow::Cow; use ndarray::Array2; use num_complex::Complex64; @@ -156,6 +156,54 @@ impl Instruction { } } + /// Returns the multi-controlled gate when this is an `McGate` instruction. + pub fn mc_gate(&self) -> Option<&MCGate> { + match self { + Self::McGate(gate) => Some(gate), + _ => None, + } + } + + /// Returns the user-defined unitary gate when this is a `UnitaryGate` instruction. + pub fn unitary_gate(&self) -> Option<&UnitaryGate> { + match self { + Self::UnitaryGate(gate) => Some(gate), + _ => None, + } + } + + /// Returns the circuit-backed gate when this is a `CircuitGate` instruction. + pub fn circuit_gate(&self) -> Option<&CircuitGate> { + match self { + Self::CircuitGate(gate) => Some(gate), + _ => None, + } + } + + /// Returns the directive when this is a `Directive` instruction. + pub fn directive(&self) -> Option { + match self { + Self::Directive(directive) => Some(*directive), + _ => None, + } + } + + /// Returns the classical data operation when this is a `ClassicalData` instruction. + pub fn classical_data(&self) -> Option<&ClassicalDataOp> { + match self { + Self::ClassicalData(operation) => Some(operation), + _ => None, + } + } + + /// Returns the classical control operation when this is a `ClassicalControl` instruction. + pub fn classical_control(&self) -> Option<&ClassicalControlOp> { + match self { + Self::ClassicalControl(operation) => Some(operation), + _ => None, + } + } + /// Returns true when this instruction directly or recursively contains a measurement. pub fn has_measurement(&self) -> bool { match self { @@ -270,23 +318,26 @@ impl Instruction { /// Computes the unitary matrix representation of the instruction. /// + /// The first qubit argument is the most-significant bit of the local + /// matrix for every supported gate, including circuit-backed UnitaryGate + /// definitions. Full circuit matrices instead use an LSB-first basis. + /// /// # Arguments /// /// * `params` - A slice of floating-point parameters (e.g., rotation angles). + /// CircuitGate values bind positionally to its declared signature. /// /// # Returns /// - /// - `Some(Cow)`: The unitary matrix for `Standard` and `Extended` gates. - /// - `None`: If the instruction is non-unitary (e.g., `Measure`, `Barrier`, `Reset`, - /// or classical control). + /// - `Some(Cow)`: A numeric matrix for a supported gate instruction. + /// - `None`: If parameters are invalid or unresolved, or the instruction has + /// no matrix (e.g., `Measure`, `Barrier`, `Reset`, or classical control). pub fn matrix(&self, params: &[f64]) -> Option>> { match self { Instruction::Standard(g) => g.matrix(params).ok(), Instruction::McGate(g) => g.matrix(params).ok(), - Instruction::UnitaryGate(g) => g.matrix_for_params(params).ok(), - Instruction::CircuitGate(g) => circuit_to_matrix(&g.circuit.circuit, None) - .ok() - .map(Cow::Owned), + Instruction::UnitaryGate(g) => g.matrix_for_params_in_gate_order(params).ok(), + Instruction::CircuitGate(g) => g.matrix_for_params(params).ok().map(Cow::Owned), Instruction::Directive(_) => None, Instruction::ClassicalData(_) => None, Instruction::Delay => None, diff --git a/crates/cqlib-core/src/circuit/gate/instruction_test.rs b/crates/cqlib-core/src/circuit/gate/instruction_test.rs index 7e8a418a..426cf7b1 100644 --- a/crates/cqlib-core/src/circuit/gate/instruction_test.rs +++ b/crates/cqlib-core/src/circuit/gate/instruction_test.rs @@ -13,9 +13,179 @@ use super::*; use crate::circuit::{ - Circuit, CircuitId, ClassicalExpr, ClassicalType, ClassicalValue, ClassicalVar, + Circuit, CircuitId, ClassicalExpr, ClassicalType, ClassicalValue, ClassicalVar, Qubit, }; +#[test] +fn circuit_backed_unitary_instruction_matrix_uses_msb_first_qubits() { + use crate::circuit::circuit_to_matrix; + use crate::circuit::test_utils::assert_matrix_approx_eq; + + for order in [vec![], vec![7], vec![0, 1], vec![1, 0], vec![9, 2, 7]] { + let mut numeric_order = order.clone(); + numeric_order.sort_unstable(); + for parameterized in [false, true] { + let mut body = + Circuit::from_qubits(order.iter().copied().map(Qubit::new).collect()).unwrap(); + if let Some(&first) = numeric_order.first() { + body.rx( + Qubit::new(first), + if parameterized { + Parameter::symbol("theta") + } else { + Parameter::from(0.7) + }, + ) + .unwrap(); + if numeric_order.len() > 1 { + body.cx( + Qubit::new(first), + Qubit::new(*numeric_order.last().unwrap()), + ) + .unwrap(); + } + } + body.set_global_phase(if parameterized { + Parameter::symbol("theta") + } else { + Parameter::from(0.7) + }); + let gate = UnitaryGate::new("positional", order.len() as u16, u16::from(parameterized)) + .with_circuit(Arc::new(FrozenCircuit::new(body.clone()))) + .unwrap(); + let params = if parameterized { vec![0.7] } else { vec![] }; + let bindings = Some(std::collections::HashMap::from([("theta", 0.7)])); + let bound = body.assign_parameters(&bindings).unwrap(); + let lsb_order: Vec = numeric_order.iter().map(|&q| q as usize).collect(); + // The definition API keeps its existing numeric-ID, LSB-first basis. + assert_matrix_approx_eq( + gate.matrix_for_params(¶ms).unwrap().as_ref(), + &circuit_to_matrix(&bound, Some(&lsb_order)).unwrap(), + 1e-12, + ); + + let instruction = Instruction::UnitaryGate(Box::new(gate)); + let matrix = instruction.matrix(¶ms).unwrap(); + let qubits: Vec = [11, 3, 8][..order.len()] + .iter() + .copied() + .map(Qubit::new) + .collect(); + let mut expected = Circuit::from_qubits(qubits.clone()).unwrap(); + if let Some(&first) = qubits.first() { + expected.rx(first, Parameter::from(0.7)).unwrap(); + if qubits.len() > 1 { + expected.cx(first, *qubits.last().unwrap()).unwrap(); + } + } + expected.set_global_phase(Parameter::from(0.7)); + let msb_order: Vec = qubits.iter().rev().map(|q| q.index()).collect(); + assert_matrix_approx_eq( + matrix.as_ref(), + &circuit_to_matrix(&expected, Some(&msb_order)).unwrap(), + 1e-12, + ); + let operation = crate::circuit::Operation { + instruction: instruction.clone(), + qubits: qubits.into_iter().collect(), + params: params + .into_iter() + .map(crate::circuit::CircuitParam::Fixed) + .collect(), + label: None, + }; + assert_matrix_approx_eq(operation.matrix().unwrap().as_ref(), matrix.as_ref(), 1e-12); + if parameterized { + for invalid in [vec![], vec![f64::NAN], vec![f64::INFINITY], vec![0.7, 0.2]] { + assert!(instruction.matrix(&invalid).is_none()); + } + } + } + } +} + +#[test] +fn unitary_instruction_matrix_keeps_explicit_matrix_order_and_precedence() { + use crate::circuit::symbolic_matrix::standard_gate_symbolic_matrix; + + let mut body = Circuit::from_qubits(vec![Qubit::new(7), Qubit::new(2)]).unwrap(); + body.cx(Qubit::new(2), Qubit::new(7)).unwrap(); + let frozen = Arc::new(FrozenCircuit::new(body)); + let numeric = StandardGate::CX.matrix(&[]).unwrap(); + for with_circuit in [false, true] { + for symbolic in [false, true] { + let gate = UnitaryGate::new("explicit_cx", 2, 0); + let gate = if symbolic { + gate.with_symbolic_matrix( + std::iter::empty::(), + standard_gate_symbolic_matrix(StandardGate::CX, &[]).unwrap(), + ) + } else { + gate.with_matrix(numeric.clone().into_owned()) + } + .unwrap(); + let gate = if with_circuit { + gate.with_circuit(frozen.clone()).unwrap() + } else { + gate + }; + let instruction = Instruction::UnitaryGate(Box::new(gate)); + let matrix = instruction.matrix(&[]).unwrap(); + assert_eq!(matrix.as_ref(), numeric.as_ref()); + assert_eq!(matches!(matrix, Cow::Borrowed(_)), !symbolic); + } + } +} + +#[test] +fn circuit_gate_operation_matrix_respects_positional_qubits() { + for order in [[0, 1], [1, 0], [7, 2]] { + let mut body = Circuit::from_qubits(order.map(Qubit::new).to_vec()).unwrap(); + body.x(Qubit::new(order[0])).unwrap(); + let instruction = body.to_gate("first_x").unwrap(); + let matrix = instruction.matrix(&[]).unwrap(); + // First argument is the MSB of a gate-local matrix: X tensor I. + for row in 0..4 { + for col in 0..4 { + let expected = if row == (col ^ 2) { 1.0 } else { 0.0 }; + assert_eq!(matrix[[row, col]], Complex64::new(expected, 0.0)); + } + } + } +} + +#[test] +fn circuit_gate_operation_matrix_binds_numeric_arguments() { + let mut body = Circuit::from_qubits(vec![Qubit::new(7)]).unwrap(); + body.rx(Qubit::new(7), Parameter::symbol("theta")).unwrap(); + let instruction = body.to_gate("rx").unwrap(); + for angle in [0.37_f64, -0.61] { + let matrix = instruction.matrix(&[angle]).unwrap(); + let mut operation = crate::circuit::Operation { + instruction: instruction.clone(), + qubits: smallvec::smallvec![Qubit::new(7)], + params: smallvec::smallvec![crate::circuit::CircuitParam::Fixed(angle)], + label: None, + }; + assert_eq!(operation.matrix().unwrap().as_ref(), matrix.as_ref()); + operation.params[0] = crate::circuit::CircuitParam::Index(0); + assert!(matches!( + operation.matrix(), + Err(crate::circuit::CircuitError::SymbolicParameterError) + )); + for row in 0..2 { + for col in 0..2 { + let expected = if row == col { + Complex64::new((angle / 2.0).cos(), 0.0) + } else { + Complex64::new(0.0, -(angle / 2.0).sin()) + }; + assert!((matrix[[row, col]] - expected).norm() < 1e-12); + } + } + } +} + #[test] fn standard_gate_query_distinguishes_instruction_kinds() { assert_eq!( @@ -255,3 +425,85 @@ fn classical_control_op_converts_to_instruction() { Instruction::ClassicalControl(ClassicalControlOp::Break) )); } + +#[test] +fn payload_accessors_match_predicates_for_every_variant() { + let circuit_id = CircuitId::new(); + let measured = ClassicalValue::new(circuit_id, 0, ClassicalType::Bit); + let circuit_gate = CircuitGate::new("composite", FrozenCircuit::new(Circuit::new(1))).unwrap(); + + let cases = [ + Instruction::Standard(StandardGate::H), + Instruction::McGate(Box::new(MCGate::new(2, StandardGate::X))), + Instruction::UnitaryGate(Box::new(UnitaryGate::new("oracle", 1, 0))), + Instruction::CircuitGate(Box::new(circuit_gate)), + Instruction::Directive(Directive::Barrier), + Instruction::ClassicalData(ClassicalDataOp::MeasureBit { result: measured }), + Instruction::ClassicalControl(ClassicalControlOp::Break), + Instruction::Delay, + ]; + + for instruction in cases { + assert_eq!( + instruction.standard_gate().is_some(), + instruction.is_standard() + ); + assert_eq!(instruction.mc_gate().is_some(), instruction.is_mcgate()); + assert_eq!( + instruction.unitary_gate().is_some(), + instruction.is_unitary() + ); + assert_eq!( + instruction.circuit_gate().is_some(), + instruction.is_circuit_gate() + ); + assert_eq!( + instruction.directive().is_some(), + instruction.is_directive() + ); + assert_eq!( + instruction.classical_data().is_some(), + instruction.is_classical_data() + ); + assert_eq!( + instruction.classical_control().is_some(), + instruction.is_classical_control() + ); + } +} + +#[test] +fn payload_accessors_return_the_stored_payload() { + let circuit_id = CircuitId::new(); + let measured = ClassicalValue::new(circuit_id, 0, ClassicalType::Bit); + let target = ClassicalVar::new(circuit_id, 0, ClassicalType::Bit); + + let mc = Instruction::McGate(Box::new(MCGate::new(2, StandardGate::RZ))); + let mc_gate = mc.mc_gate().unwrap(); + assert_eq!(mc_gate.num_ctrl_qubits(), 2); + assert_eq!(mc_gate.base_gate(), &StandardGate::RZ); + + let unitary = Instruction::UnitaryGate(Box::new(UnitaryGate::new("oracle", 2, 1))); + let unitary_gate = unitary.unitary_gate().unwrap(); + assert_eq!(unitary_gate.label(), "oracle"); + assert_eq!(unitary_gate.num_qubits(), 2); + + let circuit_gate = CircuitGate::new("composite", FrozenCircuit::new(Circuit::new(1))).unwrap(); + let circuit = Instruction::CircuitGate(Box::new(circuit_gate)); + assert_eq!(circuit.circuit_gate().unwrap().name(), "composite"); + + let directive = Instruction::Directive(Directive::Measure); + assert_eq!(directive.directive(), Some(Directive::Measure)); + + let store = Instruction::ClassicalData(ClassicalDataOp::Store { + target, + value: ClassicalExpr::value(measured), + }); + assert_eq!(store.classical_data().unwrap().target(), Some(target)); + + let control = Instruction::ClassicalControl(ClassicalControlOp::Continue); + assert!(matches!( + control.classical_control(), + Some(ClassicalControlOp::Continue) + )); +} diff --git a/crates/cqlib-core/src/circuit/gate/unitary_gate.rs b/crates/cqlib-core/src/circuit/gate/unitary_gate.rs index 9e574e15..35e104c6 100644 --- a/crates/cqlib-core/src/circuit/gate/unitary_gate.rs +++ b/crates/cqlib-core/src/circuit/gate/unitary_gate.rs @@ -286,9 +286,31 @@ impl UnitaryGate { } /// Resolves this gate into a concrete matrix for the supplied parameter values. + /// + /// Explicit matrices use MSB-first argument order. A circuit-only definition + /// retains its numeric-ID, LSB-first basis for compatibility with circuit + /// matrix construction. Use [`Instruction::matrix`](super::Instruction::matrix) + /// for a uniform MSB-first gate-local matrix. pub fn matrix_for_params( &self, params: &[f64], + ) -> Result>>, CircuitError> { + self.resolve_matrix_for_params(params, false) + } + + /// Resolves a gate-local matrix with the first argument at MSB, regardless + /// of whether the definition supplies a matrix or a circuit. + pub(crate) fn matrix_for_params_in_gate_order( + &self, + params: &[f64], + ) -> Result>>, CircuitError> { + self.resolve_matrix_for_params(params, true) + } + + fn resolve_matrix_for_params( + &self, + params: &[f64], + circuit_msb_first: bool, ) -> Result>>, CircuitError> { self.validate_param_values(params)?; @@ -323,7 +345,17 @@ impl UnitaryGate { let assigned = inner .assign_parameters(&Some(bindings)) .map_err(|_| CircuitError::SymbolicParameterError)?; - return circuit_to_matrix(&assigned, None).map(Cow::Owned); + let mut order: Vec = circuit + .qubits_in_numeric_order() + .iter() + .map(|q| q.index()) + .collect(); + if circuit_msb_first { + // circuit_to_matrix takes an LSB-first order. Generate the + // instruction basis directly instead of permuting a dense matrix. + order.reverse(); + } + return circuit_to_matrix(&assigned, Some(&order)).map(Cow::Owned); } Err(CircuitError::NoMatrixRepresentation) @@ -407,6 +439,12 @@ impl UnitaryGate { /// /// This allows the gate to be defined by its circuit decomposition, /// which is useful for inverse operations and optimization. + /// The internal qubits are mapped in ascending numeric-ID order to the + /// caller's qubits, independently of their storage order in the circuit. + /// When no explicit matrix is attached, the first such qubit is the least + /// significant bit of the derived matrix. Explicit matrices retain their + /// MSB-first argument convention; if both representations are supplied, + /// they must describe the same operation under their respective conventions. /// /// # Arguments /// diff --git a/crates/cqlib-core/src/circuit/gate/unitary_gate_test.rs b/crates/cqlib-core/src/circuit/gate/unitary_gate_test.rs index 87e83d6a..8c197ab2 100644 --- a/crates/cqlib-core/src/circuit/gate/unitary_gate_test.rs +++ b/crates/cqlib-core/src/circuit/gate/unitary_gate_test.rs @@ -16,7 +16,9 @@ use crate::circuit::gate::StandardGate; use crate::circuit::symbolic_matrix::{ SymbolicComplex, standard_gate_symbolic_matrix, symbolic_eye, }; +use crate::circuit::test_utils::assert_matrix_approx_eq; use crate::circuit::{Circuit, Parameter, Qubit}; +use crate::compile::transform::decompose::expand_definitions; use ndarray::array; use num_complex::Complex64; @@ -646,3 +648,252 @@ fn test_custom_unitary_in_composite_circuit() { } } } + +/// Check complete operators, including spectator qubits and nested CircuitGate +/// definitions, against an independently constructed positional reference. +fn assert_circuit_definition_order(transform: impl Fn(&Circuit) -> Circuit) { + let mut inner = Circuit::from_qubits(vec![Qubit::new(2), Qubit::new(0)]).unwrap(); + inner.x(Qubit::new(2)).unwrap(); + let gate = UnitaryGate::new("asymmetric_x", 2, 0) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + let mut circuit = Circuit::new(2); + circuit + .unitary(gate, vec![Qubit::new(0), Qubit::new(1)]) + .unwrap(); + let mut expected = Circuit::new(2); + expected.x(Qubit::new(1)).unwrap(); + let expected = circuit_to_matrix(&expected, None).unwrap(); + assert_matrix_approx_eq( + &circuit_to_matrix(&circuit, None).unwrap(), + &expected, + 1e-12, + ); + assert_matrix_approx_eq( + &circuit_to_matrix(&transform(&circuit), None).unwrap(), + &expected, + 1e-12, + ); + + let mut leaf = Circuit::from_qubits(vec![Qubit::new(4), Qubit::new(1)]).unwrap(); + leaf.h(Qubit::new(4)).unwrap(); + leaf.cx(Qubit::new(4), Qubit::new(1)).unwrap(); + let leaf = leaf.to_gate("storage_order_leaf").unwrap(); + + for order in [[9, 2, 5], [5, 9, 2], [2, 5, 9]] { + let mut inner = Circuit::from_qubits(order.map(Qubit::new).to_vec()).unwrap(); + inner.rx(Qubit::new(9), 0.37).unwrap(); + inner.ry(Qubit::new(2), -0.51).unwrap(); + inner.cx(Qubit::new(5), Qubit::new(9)).unwrap(); + inner.cx(Qubit::new(9), Qubit::new(2)).unwrap(); + inner.rz(Qubit::new(5), 0.29).unwrap(); + inner + .append(leaf.clone(), [Qubit::new(9), Qubit::new(5)], [], None) + .unwrap(); + // Explicit matrices use MSB-first qargs. Reverse the definition's + // numeric order when also supplying an equivalent matrix representation. + let explicit_matrix = circuit_to_matrix(&inner, Some(&[9, 5, 2])).unwrap(); + let gate = UnitaryGate::new("numeric_order_unitary", 3, 0) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + for with_matrix in [false, true] { + let gate = if with_matrix { + gate.clone().with_matrix(explicit_matrix.clone()).unwrap() + } else { + gate.clone() + }; + for args in [ + [0, 2, 3], + [0, 3, 2], + [2, 0, 3], + [2, 3, 0], + [3, 0, 2], + [3, 2, 0], + ] { + let [a, b, c] = args.map(Qubit::new); + let mut circuit = Circuit::new(4); + circuit.unitary(gate.clone(), vec![a, b, c]).unwrap(); + let mut expected = Circuit::new(4); + expected.rx(c, 0.37).unwrap(); + expected.ry(a, -0.51).unwrap(); + expected.cx(b, c).unwrap(); + expected.cx(c, a).unwrap(); + expected.rz(b, 0.29).unwrap(); + expected.h(c).unwrap(); + expected.cx(c, b).unwrap(); + let expected = circuit_to_matrix(&expected, None).unwrap(); + assert_matrix_approx_eq( + &circuit_to_matrix(&circuit, None).unwrap(), + &expected, + 1e-12, + ); + assert_matrix_approx_eq( + &circuit_to_matrix(&transform(&circuit), None).unwrap(), + &expected, + 1e-12, + ); + } + } + } +} + +#[test] +fn circuit_definition_order_survives_expansion() { + assert_circuit_definition_order(|circuit| expand_definitions(circuit).unwrap()); +} + +#[test] +fn circuit_definition_order_survives_qasm2() { + assert_circuit_definition_order(|circuit| { + crate::ir::qasm2::load::loads(&crate::ir::qasm2::dump::dumps(circuit).unwrap()).unwrap() + }); +} + +#[test] +fn circuit_definition_order_survives_qasm3() { + assert_circuit_definition_order(|circuit| { + crate::ir::qasm3::load::loads(&crate::ir::qasm3::dump::dumps(circuit).unwrap()).unwrap() + }); +} + +#[test] +fn circuit_definition_order_survives_compilation() { + use crate::compile::resource::ResourcePolicy; + use crate::compile::{CompileConfig, CompileMode, CompileTarget, compile}; + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + assert_circuit_definition_order(|circuit| { + compile( + circuit, + CompileConfig { + mode, + target: CompileTarget::Logical, + resource_policy: ResourcePolicy::default(), + }, + ) + .unwrap() + .circuit + }); + } +} + +#[test] +fn circuit_definition_order_preserves_device_layout_and_basis() { + use crate::compile::resource::ResourcePolicy; + use crate::compile::{CompileConfig, CompileMode, CompileTarget, DeviceCompileTarget, compile}; + use crate::device::{Device, Layout}; + + let mut inner = Circuit::from_qubits(vec![Qubit::new(2), Qubit::new(0)]).unwrap(); + inner.x(Qubit::new(2)).unwrap(); + inner.cx(Qubit::new(2), Qubit::new(0)).unwrap(); + let gate = UnitaryGate::new("device_unitary", 2, 0) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + let mut circuit = Circuit::new(2); + circuit + .unitary(gate, vec![Qubit::new(0), Qubit::new(1)]) + .unwrap(); + let device = Device::line("unitary-ports", 2) + .unwrap() + .with_native_gates(vec![ + StandardGate::X.into(), + StandardGate::H.into(), + StandardGate::CX.into(), + ]) + .unwrap(); + let layout = Layout::from_pairs(&[(0, 1), (1, 0)], 2).unwrap(); + // Internal 2 -> argument 1 -> physical 0. The CX direction is native on + // the device even though its logical arguments are in reverse order. + let mut expected = Circuit::new(2); + expected.x(Qubit::new(0)).unwrap(); + expected.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + let result = compile( + &circuit, + CompileConfig { + mode, + target: CompileTarget::Device(DeviceCompileTarget { + device: device.clone(), + initial_layout: Some(layout.clone()), + seed: Some(47), + }), + resource_policy: ResourcePolicy::default(), + }, + ) + .unwrap(); + device.validate_circuit(&result.circuit).unwrap(); + let metadata = result.device_metadata.unwrap(); + assert_eq!(metadata.initial_layout, layout); + assert_eq!(metadata.final_layout, layout); + assert_matrix_approx_eq( + &circuit_to_matrix(&result.circuit, None).unwrap(), + &circuit_to_matrix(&expected, None).unwrap(), + 1e-9, + ); + } +} + +#[test] +fn circuit_definition_order_preserves_nested_symbolic_parameters_and_phase() { + use crate::circuit::symbolic_matrix::{circuit_to_symbolic_matrix, evaluate_symbolic_matrix}; + let mut inner = Circuit::from_qubits(vec![Qubit::new(2), Qubit::new(0)]).unwrap(); + inner.rx(Qubit::new(2), Parameter::symbol("theta")).unwrap(); + inner.cx(Qubit::new(2), Qubit::new(0)).unwrap(); + inner.set_global_phase(Parameter::symbol("theta") * 0.25); + let gate = UnitaryGate::new("symbolic_unitary", 2, 1) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + let mut middle = Circuit::from_qubits(vec![Qubit::new(7), Qubit::new(3)]).unwrap(); + middle + .unitary_with_params( + gate, + vec![Qubit::new(3), Qubit::new(7)], + [Parameter::symbol("alpha").into()], + ) + .unwrap(); + let wrapper = middle.to_gate("storage_order_wrapper").unwrap(); + let mut circuit = Circuit::new(3); + circuit + .append( + wrapper, + [Qubit::new(2), Qubit::new(0)], + [crate::circuit::ParameterValue::Param( + Parameter::symbol("t") + 0.1_f64, + )], + None, + ) + .unwrap(); + let mut expected = Circuit::new(3); + expected + .rx(Qubit::new(2), Parameter::symbol("t") + 0.1) + .unwrap(); + expected.cx(Qubit::new(2), Qubit::new(0)).unwrap(); + expected.set_global_phase((Parameter::symbol("t") + 0.1) * 0.25); + + // Build the nested symbolic matrix before expansion, exercising numeric-order + // UnitaryGate and storage-order CircuitGate caches in the same expression. + let symbolic = circuit_to_symbolic_matrix(&circuit, None).unwrap(); + let expanded = expand_definitions(&circuit).unwrap(); + let expanded_symbolic = circuit_to_symbolic_matrix(&expanded, None).unwrap(); + for value in [0.0, 0.37, -0.51] { + let bindings = Some(HashMap::from([("t", value)])); + let expected = + circuit_to_matrix(&expected.assign_parameters(&bindings).unwrap(), None).unwrap(); + assert_matrix_approx_eq( + &evaluate_symbolic_matrix(&symbolic, &bindings).unwrap(), + &expected, + 1e-12, + ); + assert_matrix_approx_eq( + &evaluate_symbolic_matrix(&expanded_symbolic, &bindings).unwrap(), + &expected, + 1e-12, + ); + let bound = circuit.assign_parameters(&bindings).unwrap(); + assert_matrix_approx_eq(&circuit_to_matrix(&bound, None).unwrap(), &expected, 1e-12); + assert_matrix_approx_eq( + &circuit_to_matrix(&expand_definitions(&bound).unwrap(), None).unwrap(), + &expected, + 1e-12, + ); + } +} diff --git a/crates/cqlib-core/src/circuit/operation.rs b/crates/cqlib-core/src/circuit/operation.rs index 4bfafecd..1d4b9ad7 100644 --- a/crates/cqlib-core/src/circuit/operation.rs +++ b/crates/cqlib-core/src/circuit/operation.rs @@ -102,6 +102,9 @@ impl Operation { /// # Returns /// /// * `Ok(Cow)` - The unitary matrix. It may be borrowed (static) or owned (computed). + /// All gate matrices put the first qubit argument at the most-significant + /// local basis bit, including circuit-backed UnitaryGate and CircuitGate + /// definitions. Full circuit matrices instead use an LSB-first basis. /// * `Err(CircuitError)` - If the operation is non-unitary or contains an /// unresolved symbolic parameter. /// diff --git a/crates/cqlib-core/src/circuit/parameter.rs b/crates/cqlib-core/src/circuit/parameter.rs index 10c0ef31..18bfe78e 100644 --- a/crates/cqlib-core/src/circuit/parameter.rs +++ b/crates/cqlib-core/src/circuit/parameter.rs @@ -40,7 +40,323 @@ use std::collections::{HashMap, HashSet}; use std::fmt; use std::ops::{Add, Div, Mul, Neg, Sub}; use std::str::FromStr; -use symb_anafis::{Expr, Simplify, parse, symb}; +use symb_anafis::{Expr, Simplify, parse, symb, visitor::ExprView}; + +// The engine's map() treats polynomials as opaque and visits rebuilt nodes. +// Walk the public view instead: it exposes polynomial terms, and replacement +// expressions are returned immediately without being traversed themselves. +fn substitute_parameter_expr<'a>(expr: &Expr, lookup: &impl Fn(&str) -> Option<&'a Expr>) -> Expr { + match expr.view() { + ExprView::Number(_) => expr.clone(), + ExprView::Symbol(name) => lookup(&name).cloned().unwrap_or_else(|| expr.clone()), + ExprView::Sum(children) | ExprView::Product(children) => { + let mapped: Vec<_> = children + .iter() + .map(|child| substitute_parameter_expr(child, lookup)) + .collect(); + if children.iter().zip(&mapped).all(|(a, b)| a.as_ref() == b) { + return expr.clone(); + } + + // Smart sum/product constructors can prune tiny coefficients. + // Construct a template of distinct function calls first, then use + // map() only on that template, whose children have no polynomials. + // Inserted expressions never pass through the smart constructors. + let slots = (0..mapped.len()) + .map(|i| Expr::func("__cqlib_substitution_slot", Expr::number(i as f64))) + .collect(); + let template = if matches!(expr.view(), ExprView::Sum(_)) { + Expr::sum(slots) + } else { + Expr::product(slots) + }; + let slots = match template.view() { + ExprView::Sum(slots) | ExprView::Product(slots) => slots.into_owned(), + _ => return mapped.into_iter().next().unwrap_or(template), + }; + // Match in template order so reconstruction preserves the original + // child order even if construction sorted the placeholder nodes. + let replacements: HashMap<_, _> = slots + .into_iter() + .map(|slot| (*slot).clone()) + .zip(mapped) + .collect(); + template.map(|node| { + replacements + .get(node) + .cloned() + .unwrap_or_else(|| node.clone()) + }) + } + ExprView::Div(lhs, rhs) => { + let a = substitute_parameter_expr(lhs, lookup); + let b = substitute_parameter_expr(rhs, lookup); + if &a == lhs && &b == rhs { + expr.clone() + } else { + div_parameter_expr(a, b) + } + } + ExprView::Pow(base, exponent) => { + let a = substitute_parameter_expr(base, lookup); + let b = substitute_parameter_expr(exponent, lookup); + if &a == base && &b == exponent { + expr.clone() + } else { + Expr::pow_static(a, b) + } + } + ExprView::Function { name, args } => { + let mapped: Vec<_> = args + .iter() + .map(|arg| substitute_parameter_expr(arg, lookup)) + .collect(); + if args.iter().zip(&mapped).all(|(a, b)| a.as_ref() == b) { + expr.clone() + } else { + Expr::func_multi(name, mapped) + } + } + ExprView::Derivative { inner, var, order } => { + let mapped = substitute_parameter_expr(inner, lookup); + if &mapped == inner { + expr.clone() + } else { + Expr::derivative(mapped, var, order) + } + } + } +} + +// Integral coefficients in the exactly representable integer range cannot +// trigger the engine's near-zero/near-one pruning. Ordinary sums of symbols +// therefore avoid coefficient collection and expression rebuilding entirely. +fn needs_affine_protection(expr: &Expr) -> bool { + match expr.view() { + ExprView::Number(value) => value.fract() != 0.0 || value.abs() > (1u64 << 53) as f64, + ExprView::Sum(children) | ExprView::Product(children) => { + children.iter().any(|child| needs_affine_protection(child)) + } + ExprView::Div(numerator, denominator) => { + needs_affine_protection(numerator) + || denominator.as_number().is_some_and(|value| { + value != 0.0 && needs_affine_protection(&Expr::number(1.0 / value)) + }) + } + _ => false, + } +} + +type AffineCoefficients = HashMap, f64>; + +// Coefficients are collected once per input, using hashed symbol keys. Building +// a replacement AST is deferred until the engine actually changes a coefficient. +fn affine_coefficients(inputs: &[(&Expr, f64)]) -> Option { + fn collect(expr: &Expr, scale: f64, terms: &mut AffineCoefficients) -> Option<()> { + match expr.view() { + ExprView::Number(value) => *terms.entry(None).or_default() += scale * value, + ExprView::Symbol(_) => *terms.entry(Some(expr.clone())).or_default() += scale, + ExprView::Sum(children) => { + for child in children.iter() { + collect(child, scale, terms)?; + } + } + ExprView::Product(children) => { + let mut scale = scale; + let mut symbolic = None; + for child in children.iter() { + if let Some(value) = child.as_number() { + scale *= value; + } else if symbolic.replace(child).is_some() { + return None; + } + } + if let Some(child) = symbolic { + collect(child, scale, terms)?; + } else { + *terms.entry(None).or_default() += scale; + } + } + ExprView::Div(numerator, denominator) => { + let divisor = denominator.as_number()?; + if divisor == 0.0 { + return None; + } + collect(numerator, scale / divisor, terms)?; + } + _ => return None, + } + Some(()) + } + + let mut terms = HashMap::new(); + for (expr, scale) in inputs { + collect(expr, *scale, &mut terms)?; + } + if terms.values().any(|coefficient| !coefficient.is_finite()) { + return None; + } + terms.retain(|_, coefficient| *coefficient != 0.0); + Some(terms) +} + +fn weighted_symbol(symbol: Expr, coefficient: f64) -> Expr { + if coefficient == 0.0 { + return Expr::number(0.0); + } + if coefficient == 1.0 { + return symbol; + } + let product = Expr::product(vec![Expr::number(coefficient), symbol.clone()]); + if let ExprView::Product(factors) = product.view() + && factors + .iter() + .any(|factor| factor.as_number() == Some(coefficient)) + { + return product; + } + // Public map() reconstructs products without approximate numeric pruning. + // If construction rounded a near-unit coefficient, insert its exact value + // into a non-unit product template after construction. + Expr::product(vec![Expr::number(2.0), symbol]).map(|factor| { + if factor.as_number() == Some(2.0) { + Expr::number(coefficient) + } else { + factor.clone() + } + }) +} + +fn affine_expr(terms: &AffineCoefficients) -> Expr { + // Construct a sum of distinct unit-weight symbols before inserting weights, + // preventing automatic polynomial conversion from deleting small terms. + let unit_sum = Expr::sum( + terms + .keys() + .map(|symbol| symbol.clone().unwrap_or_else(|| Expr::number(1.0))) + .collect(), + ); + unit_sum.map(|node| { + if node.as_number() == Some(1.0) { + Expr::number(terms.get(&None).copied().unwrap_or(1.0)) + } else if matches!(node.view(), ExprView::Symbol(_)) { + weighted_symbol( + node.clone(), + terms.get(&Some(node.clone())).copied().unwrap_or(1.0), + ) + } else { + node.clone() + } + }) +} + +fn preserve_affine(expected: Option, fallback: Expr) -> Expr { + match expected { + Some(expected) if expected.keys().all(Option::is_none) => { + Expr::number(expected.get(&None).copied().unwrap_or(0.0)) + } + Some(expected) if affine_coefficients(&[(&fallback, 1.0)]).as_ref() != Some(&expected) => { + affine_expr(&expected) + } + _ => fallback, + } +} + +fn add_parameter_expr(lhs: Expr, rhs: Expr) -> Expr { + if let (Some(a), Some(b)) = (lhs.as_number(), rhs.as_number()) { + return Expr::number(a + b); + } + if !needs_affine_protection(&lhs) && !needs_affine_protection(&rhs) { + return lhs + rhs; + } + let affine = affine_coefficients(&[(&lhs, 1.0), (&rhs, 1.0)]); + preserve_affine(affine, lhs + rhs) +} + +fn sub_parameter_expr(lhs: Expr, rhs: Expr) -> Expr { + if let (Some(a), Some(b)) = (lhs.as_number(), rhs.as_number()) { + return Expr::number(a - b); + } + if !needs_affine_protection(&lhs) && !needs_affine_protection(&rhs) { + return lhs - rhs; + } + let affine = affine_coefficients(&[(&lhs, 1.0), (&rhs, -1.0)]); + preserve_affine(affine, lhs - rhs) +} + +// The common rotation-angle case needs neither a coefficient map nor a second +// symbolic operation. Handle one weighted symbol directly, including rescaling. +fn scaled_symbol(expr: &Expr, scale: f64) -> Option { + let (symbol, coefficient) = match expr.view() { + ExprView::Symbol(_) => (expr.clone(), scale), + ExprView::Product(children) if children.len() == 2 => { + let (number, symbol) = if let Some(number) = children[0].as_number() { + (number, &children[1]) + } else { + (children[1].as_number()?, &children[0]) + }; + if !matches!(symbol.view(), ExprView::Symbol(_)) { + return None; + } + ((**symbol).clone(), number * scale) + } + _ => return None, + }; + coefficient + .is_finite() + .then(|| weighted_symbol(symbol, coefficient)) +} + +fn mul_parameter_expr(lhs: Expr, rhs: Expr) -> Expr { + if let (Some(a), Some(b)) = (lhs.as_number(), rhs.as_number()) { + return Expr::number(a * b); + } + let affine = if let Some(scale) = lhs.as_number() { + if let Some(expr) = scaled_symbol(&rhs, scale) { + return expr; + } + if !needs_affine_protection(&lhs) && !needs_affine_protection(&rhs) { + return lhs * rhs; + } + affine_coefficients(&[(&rhs, scale)]) + } else if let Some(scale) = rhs.as_number() { + if let Some(expr) = scaled_symbol(&lhs, scale) { + return expr; + } + if !needs_affine_protection(&lhs) && !needs_affine_protection(&rhs) { + return lhs * rhs; + } + affine_coefficients(&[(&lhs, scale)]) + } else { + None + }; + preserve_affine(affine, lhs * rhs) +} + +fn div_parameter_expr(lhs: Expr, rhs: Expr) -> Expr { + if let (Some(a), Some(b)) = (lhs.as_number(), rhs.as_number()) + && b != 0.0 + { + return Expr::number(a / b); + } + let affine = if let Some(divisor) = rhs.as_number().filter(|value| *value != 0.0) { + affine_coefficients(&[(&lhs, 1.0)]).and_then(|mut terms| { + // Divide coefficients directly: the reciprocal of a subnormal + // divisor can overflow even when the quotient is representable. + for coefficient in terms.values_mut() { + *coefficient /= divisor; + } + if terms.values().any(|coefficient| !coefficient.is_finite()) { + return None; + } + terms.retain(|_, coefficient| *coefficient != 0.0); + Some(terms) + }) + } else { + None + }; + preserve_affine(affine, lhs / rhs) +} /// A symbolic or numeric parameter used to represent gate angles and other /// continuous values in a quantum circuit. @@ -261,6 +577,11 @@ impl Parameter { /// /// Simplification is performed in a domain-safe mode to avoid invalid /// transformations (e.g. taking the log of a potentially negative number). + /// For affine sums, scalar products and division by numeric constants, + /// nonzero `f64` coefficients and cancellation results are preserved without + /// tolerance pruning. Numeric literals are retained exactly. Floating-point + /// rounding, overflow and underflow still apply. Parsing and general + /// nonlinear simplification use the symbolic engine's own numeric policy. /// /// # Examples /// @@ -273,8 +594,16 @@ impl Parameter { /// assert_eq!(simplified.to_string(), "θ"); /// ``` pub fn simplify(&self) -> Result { + if self.expr.as_number().is_some() { + return Ok(self.clone()); + } + let affine = needs_affine_protection(&self.expr) + .then(|| affine_coefficients(&[(&self.expr, 1.0)])) + .flatten(); let expr = Simplify::new().domain_safe(true).simplify(&self.expr)?; - Ok(Self { expr }) + Ok(Self { + expr: preserve_affine(affine, expr), + }) } /// Returns the numeric value of this parameter without symbolic @@ -292,10 +621,11 @@ impl Parameter { /// Returns the canonical storage form of this parameter expression. /// - /// The parameter is first simplified. If the simplified expression has no - /// free symbols, it is evaluated to a concrete finite value and rebuilt as - /// a numeric parameter. This also normalizes `-0.0` to `0.0`, giving circuit - /// operation storage a stable representation for equivalent constants. + /// A constant expression is evaluated before symbolic simplification. If + /// simplification eliminates all symbols, the result is also evaluated and + /// rebuilt as a finite numeric parameter. This also normalizes `-0.0` to + /// `0.0`, giving circuit operation storage a stable representation for + /// equivalent constants. /// /// Symbolic expressions are returned in their simplified form. This method /// does not intern symbolic parameters into any circuit; use @@ -308,6 +638,11 @@ impl Parameter { /// Returns [`ParameterError`] if simplification fails, a constant expression /// cannot be evaluated, or the evaluated constant is not finite. pub fn canonicalized(&self) -> Result { + // Evaluate constant expressions before any approximate symbolic rewrite. + if self.get_symbols().is_empty() { + let value = self.evaluate(&None)?; + return Ok(Parameter::from(if value == 0.0 { 0.0 } else { value })); + } let simplified = self.simplify()?; if simplified.get_symbols().is_empty() { @@ -525,6 +860,7 @@ impl Parameter { /// Substitutes every occurrence of `symbol` in this expression with /// `param`, returning the resulting expression. + /// The inserted expression is not visited again; the original is unchanged. /// /// # Examples /// @@ -539,7 +875,9 @@ impl Parameter { pub fn replace(&self, symbol: &str, param: impl Into) -> Self { let p: Self = param.into(); Self { - expr: self.expr.substitute(symbol, &p.expr), + expr: substitute_parameter_expr(&self.expr, &|name| { + (name == symbol).then_some(&p.expr) + }), } } @@ -566,12 +904,13 @@ impl Parameter { .map(|_| symbol) } - /// Substitutes every bound symbol in this expression and simplifies when possible. + /// Simultaneously substitutes bound symbols and simplifies when possible. + /// + /// Replacement expressions are inserted as-is, without applying other + /// bindings to them. The result is independent of binding iteration order, + /// and the original expression is unchanged. pub fn substitute_many(&self, bindings: &HashMap) -> Self { - let mut substituted = self.clone(); - for (symbol, value) in bindings { - substituted = substituted.replace(symbol, value.clone()); - } + let substituted = self.substitute_many_simultaneous(bindings); substituted.simplify().unwrap_or(substituted) } @@ -586,15 +925,8 @@ impl Parameter { if bindings.is_empty() { return self.clone(); } - let replacements = bindings - .iter() - .map(|(symbol, replacement)| (Self::symbol(symbol).expr, &replacement.expr)) - .collect::>(); - Self::new(self.expr.map(|node| { - replacements - .iter() - .find(|(symbol, _)| node == symbol) - .map_or_else(|| node.clone(), |(_, replacement)| (*replacement).clone()) + Self::new(substitute_parameter_expr(&self.expr, &|name| { + bindings.get(name).map(|replacement| &replacement.expr) })) } @@ -812,7 +1144,8 @@ impl From for Parameter { /// type `$t` in both directions (e.g. `Parameter + f64` and `f64 + Parameter`). /// /// The implementation converts `$t` to `Parameter` via `Parameter::from`, extracts the -/// underlying `Expr`, and delegates to the corresponding `Expr` operator. +/// underlying `Expr`, and preserves affine coefficients before falling back to +/// the corresponding symbolic engine operator. macro_rules! impl_ops_for_type { ($t:ty) => { // Parameter + T @@ -822,8 +1155,8 @@ macro_rules! impl_ops_for_type { Self { // 1. `Parameter::from(rhs)` converts the primitive to `Parameter`. // 2. `.expr` unwraps the underlying `Expr` node. - // 3. `self.expr + ...` invokes `symb_anafis`'s `Add` impl. - expr: self.expr + Parameter::from(rhs).expr, + // 3. Preserve affine coefficients before general symbolic addition. + expr: add_parameter_expr(self.expr, Parameter::from(rhs).expr), } } } @@ -833,7 +1166,7 @@ macro_rules! impl_ops_for_type { type Output = Parameter; fn add(self, rhs: Parameter) -> Self::Output { Parameter { - expr: Parameter::from(self).expr + rhs.expr, + expr: add_parameter_expr(Parameter::from(self).expr, rhs.expr), } } } @@ -843,7 +1176,7 @@ macro_rules! impl_ops_for_type { type Output = Parameter; fn sub(self, rhs: $t) -> Self::Output { Self { - expr: self.expr - Parameter::from(rhs).expr, + expr: sub_parameter_expr(self.expr, Parameter::from(rhs).expr), } } } @@ -853,7 +1186,7 @@ macro_rules! impl_ops_for_type { type Output = Parameter; fn sub(self, rhs: Parameter) -> Self::Output { Parameter { - expr: Parameter::from(self).expr - rhs.expr, + expr: sub_parameter_expr(Parameter::from(self).expr, rhs.expr), } } } @@ -863,7 +1196,7 @@ macro_rules! impl_ops_for_type { type Output = Parameter; fn mul(self, rhs: $t) -> Self::Output { Self { - expr: self.expr * Parameter::from(rhs).expr, + expr: mul_parameter_expr(self.expr, Parameter::from(rhs).expr), } } } @@ -873,7 +1206,7 @@ macro_rules! impl_ops_for_type { type Output = Parameter; fn mul(self, rhs: Parameter) -> Self::Output { Parameter { - expr: Parameter::from(self).expr * rhs.expr, + expr: mul_parameter_expr(Parameter::from(self).expr, rhs.expr), } } } @@ -883,7 +1216,7 @@ macro_rules! impl_ops_for_type { type Output = Parameter; fn div(self, rhs: $t) -> Self::Output { Self { - expr: self.expr / Parameter::from(rhs).expr, + expr: div_parameter_expr(self.expr, Parameter::from(rhs).expr), } } } @@ -893,7 +1226,7 @@ macro_rules! impl_ops_for_type { type Output = Parameter; fn div(self, rhs: Parameter) -> Self::Output { Parameter { - expr: Parameter::from(self).expr / rhs.expr, + expr: div_parameter_expr(Parameter::from(self).expr, rhs.expr), } } } @@ -919,15 +1252,15 @@ impl_ops_for_type!(u32); /// Cloning `Expr` is inexpensive because `symb_anafis` uses reference-counted /// node sharing internally. macro_rules! impl_binary_op_ref { - ($($trait:ident, $method:ident),* $(,)?) => { + ($($trait:ident, $method:ident, $expr_method:ident);* $(;)?) => { $( // 1. Parameter op Parameter — both sides consumed. impl $trait for Parameter { type Output = Parameter; fn $method(self, rhs: Parameter) -> Self::Output { Parameter { - // Delegate directly to the underlying `Expr` operator. - expr: self.expr.$method(rhs.expr), + // Preserve affine coefficients before general symbolic arithmetic. + expr: $expr_method(self.expr, rhs.expr), } } } @@ -939,7 +1272,7 @@ macro_rules! impl_binary_op_ref { Parameter { // `Expr::clone` is cheap — the tree uses Arc-based // node sharing inside `symb_anafis`. - expr: self.expr.clone().$method(rhs.expr.clone()), + expr: $expr_method(self.expr.clone(), rhs.expr.clone()), } } } @@ -949,7 +1282,7 @@ macro_rules! impl_binary_op_ref { type Output = Parameter; fn $method(self, rhs: &'a Parameter) -> Self::Output { Parameter { - expr: self.expr.$method(rhs.expr.clone()), + expr: $expr_method(self.expr, rhs.expr.clone()), } } } @@ -959,7 +1292,7 @@ macro_rules! impl_binary_op_ref { type Output = Parameter; fn $method(self, rhs: Parameter) -> Self::Output { Parameter { - expr: self.expr.clone().$method(rhs.expr), + expr: $expr_method(self.expr.clone(), rhs.expr), } } } @@ -968,10 +1301,10 @@ macro_rules! impl_binary_op_ref { } impl_binary_op_ref! { - Add, add, - Sub, sub, - Mul, mul, - Div, div, + Add, add, add_parameter_expr; + Sub, sub, sub_parameter_expr; + Mul, mul, mul_parameter_expr; + Div, div, div_parameter_expr; } // Implement Neg for owned Parameter @@ -979,7 +1312,7 @@ impl Neg for Parameter { type Output = Parameter; fn neg(self) -> Self::Output { Parameter { - expr: self.expr.neg(), + expr: mul_parameter_expr(Expr::number(-1.0), self.expr), } } } @@ -989,7 +1322,7 @@ impl Neg for &Parameter { type Output = Parameter; fn neg(self) -> Self::Output { Parameter { - expr: self.expr.clone().neg(), + expr: mul_parameter_expr(Expr::number(-1.0), self.expr.clone()), } } } diff --git a/crates/cqlib-core/src/circuit/parameter_test.rs b/crates/cqlib-core/src/circuit/parameter_test.rs index 8fe576f2..b427a713 100644 --- a/crates/cqlib-core/src/circuit/parameter_test.rs +++ b/crates/cqlib-core/src/circuit/parameter_test.rs @@ -11,6 +11,8 @@ // that they have been altered from the originals. use super::Parameter; +use crate::circuit::circuit_impl::Circuit; +use crate::circuit::circuit_to_matrix::circuit_to_matrix; use std::collections::{HashMap, HashSet}; use std::f64::consts::{E, PI}; @@ -1136,6 +1138,111 @@ fn test_canonicalized_folds_constant_expression() { assert_eq!(canonical.evaluate(&None).unwrap(), 0.0); } +#[test] +fn affine_cancellation_preserves_small_constants_without_false_symbols() { + let t = Parameter::symbol("t"); + let u = Parameter::symbol("u"); + let q: Parameter = t * 1e-16 + u * 2e-16; + for constant in [3e-16, -3e-16, f64::from_bits(1), 0.0] { + let p = q.clone() + constant; + let result = (p - &q).canonicalized().unwrap(); + assert!(result.get_symbols().is_empty(), "{constant:?}: {result}"); + assert_eq!(result.evaluate(&None).unwrap(), constant); + assert_eq!( + result.simplify().unwrap().evaluate(&None).unwrap(), + constant + ); + assert_eq!(result.canonicalized().unwrap(), result); + assert_eq!( + (result.clone() + 0.0_f64).evaluate(&None).unwrap(), + constant + ); + if constant.abs() == 3e-16 { + let angle: Parameter = result * 1e16; + let mut circuit = Circuit::new(1); + circuit.rz(circuit.qubits()[0], angle).unwrap(); + assert!(circuit.symbols().is_empty()); + let matrix = circuit_to_matrix(&circuit, None).unwrap(); + let expected = num_complex::Complex64::from_polar(1.0, -constant * 1e16 / 2.0); + assert!((matrix[[0, 0]] - expected).norm() < 1e-14); + } + } +} + +#[test] +fn affine_scaling_preserves_near_unit_and_subnormal_weights() { + let t = Parameter::symbol("t"); + let bindings = Some(HashMap::from([("t", 1.0)])); + for coefficient in [ + f64::from_bits(1), + 1e-16, + -1e-16, + 0.375, + 1.0 - f64::EPSILON, + 1.0 + f64::EPSILON, + ] { + let weighted = t.clone() * coefficient; + let canonical = weighted.canonicalized().unwrap(); + assert!(canonical.get_symbols().contains("t")); + assert_eq!(canonical.evaluate(&bindings).unwrap(), coefficient); + let rescaled: Parameter = canonical * 2.0; + assert_eq!( + rescaled + .canonicalized() + .unwrap() + .evaluate(&bindings) + .unwrap(), + coefficient * 2.0 + ); + } +} + +#[test] +fn affine_constant_division_preserves_small_coefficients() { + let t = Parameter::symbol("t"); + let divisor = Parameter::from(1e16); + for (expr, expected) in [ + (t.clone() / 1e16, 1.0), + (&t / &divisor, 1.0), + ((t.clone() * 1e-16) / 2.0, 0.5), + ((t.clone() / 1e16) / 2.0, 0.5), + (t.clone() / -1e16, -1.0), + ] { + let canonical = expr.canonicalized().unwrap(); + assert!(canonical.get_symbols().contains("t")); + assert_eq!( + canonical + .evaluate(&Some(HashMap::from([("t", 1e16)]))) + .unwrap(), + expected + ); + } + let tiny = f64::from_bits(1); + assert_eq!((Parameter::from(tiny) / tiny).evaluate(&None).unwrap(), 1.0); + let quotient: Parameter = (t.clone() * tiny) / tiny; + assert_eq!( + quotient + .canonicalized() + .unwrap() + .evaluate(&Some(HashMap::from([("t", 1.0)]))) + .unwrap(), + 1.0 + ); + assert_eq!( + Parameter::from(tiny) + .canonicalized() + .unwrap() + .evaluate(&None) + .unwrap(), + tiny + ); + let cancelled: Parameter = t.clone() / 1e16 - t / 1e16; + assert_eq!( + cancelled.canonicalized().unwrap().evaluate(&None).unwrap(), + 0.0 + ); +} + #[test] fn test_canonicalized_normalizes_negative_zero() { let canonical = Parameter::from(-0.0).canonicalized().unwrap(); @@ -1212,3 +1319,265 @@ fn simultaneous_substitution_does_not_revisit_replacement_expressions() { assert_eq!(substituted.get_symbols(), HashSet::from(["b".to_string()])); } + +#[test] +fn substitution_swaps_symbols_in_either_binding_order() { + let x = Parameter::symbol("x"); + let y = Parameter::symbol("y"); + let expression: Parameter = x.clone() + y.clone() * 2.0; + let values = Some(HashMap::from([("x", 1.0), ("y", 3.0)])); + for pairs in [ + [("x", y.clone()), ("y", x.clone())], + [("y", x.clone()), ("x", y.clone())], + ] { + let bindings = pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect(); + for result in [ + expression.substitute_many(&bindings), + expression.substitute_many_simultaneous(&bindings), + ] { + assert_eq!(result.evaluate(&values).unwrap(), 5.0); + assert_eq!( + result.get_symbols(), + HashSet::from(["x".into(), "y".into()]) + ); + } + } + assert_eq!(expression.evaluate(&values).unwrap(), 7.0); +} + +#[test] +fn substitution_inserts_replacements_without_cascading() { + let x = Parameter::symbol("x"); + let y = Parameter::symbol("y"); + let z = Parameter::symbol("z"); + let values = Some(HashMap::from([("x", 2.0), ("y", 10.0), ("z", 20.0)])); + let cases = [ + ( + x.clone(), + vec![("x", y.clone() + 1.0), ("y", Parameter::from(2.0))], + 11.0, + ), + (x.clone(), vec![("x", x.clone() + 1.0)], 3.0), + ( + x.clone(), + vec![ + ("x", y.clone() + z.clone()), + ("y", Parameter::from(1.0)), + ("z", Parameter::from(2.0)), + ], + 30.0, + ), + ( + x.clone() + y.clone() * 2.0 + z.clone() * 3.0, + vec![("x", y), ("y", z), ("z", x)], + 56.0, + ), + ]; + for (expression, pairs, expected) in cases { + let bindings = pairs.into_iter().map(|(k, v)| (k.to_string(), v)).collect(); + for result in [ + expression.substitute_many(&bindings), + expression.substitute_many_simultaneous(&bindings), + ] { + assert_eq!(result.evaluate(&values).unwrap(), expected); + } + } +} + +#[test] +fn substitution_preserves_unbound_symbols_constants_and_noops() { + let expression = Parameter::symbol("x") + Parameter::symbol("y"); + let values = Some(HashMap::from([("x", 2.0), ("y", 3.0), ("z", 4.0)])); + for bindings in [ + HashMap::new(), + HashMap::from([("missing".into(), Parameter::symbol("z"))]), + ] { + assert_eq!( + expression + .substitute_many(&bindings) + .evaluate(&values) + .unwrap(), + 5.0 + ); + assert_eq!( + expression.substitute_many_simultaneous(&bindings), + expression + ); + } + let bindings = HashMap::from([ + ("x".into(), Parameter::symbol("z") + 1.0), + ("y".into(), Parameter::from(2.0)), + ]); + assert_eq!( + expression + .substitute_many(&bindings) + .evaluate(&values) + .unwrap(), + 7.0 + ); + assert_eq!( + Parameter::from(0.25).substitute_many(&bindings), + Parameter::from(0.25) + ); + assert_eq!( + expression.replace("missing", Parameter::from(0.0)), + expression + ); +} + +#[test] +fn substitution_reaches_polynomial_bases_and_nested_operations() { + let x = Parameter::symbol("x"); + let y = Parameter::symbol("y"); + let values = Some(HashMap::from([("y", 0.5)])); + let natural_polynomial: Parameter = x.clone() * x.clone() + x.clone() + 1.0; + let base = x.sin(); + let function_polynomial: Parameter = base.clone() * base.clone() + base * 2.0 + 1.0; + let nested = (natural_polynomial.clone() / (x.clone() + Parameter::from(2.0))).cos() + + x.clone().pow(y.clone() + 1.0); + let bindings = HashMap::from([("x".into(), y.clone())]); + for expression in [natural_polynomial, function_polynomial, nested] { + let expected = expression + .evaluate(&Some(HashMap::from([("x", 0.5), ("y", 0.5)]))) + .unwrap(); + for result in [ + expression.replace("x", y.clone()), + expression.substitute_many(&bindings), + expression.substitute_many_simultaneous(&bindings), + ] { + assert_eq!(result.get_symbols(), HashSet::from(["y".into()])); + assert!((result.evaluate(&values).unwrap() - expected).abs() < 1e-12); + } + } +} + +#[test] +fn substitution_does_not_revisit_rebuilt_division_or_power() { + let x = Parameter::symbol("x"); + let y = Parameter::symbol("y"); + let bindings = HashMap::from([ + ("x".into(), Parameter::symbol("z")), + ("y".into(), Parameter::from(1.0)), + ("z".into(), Parameter::from(2.0)), + ]); + for expression in [x.clone() / y.clone(), x.pow(y)] { + for result in [ + expression.substitute_many(&bindings), + expression.substitute_many_simultaneous(&bindings), + ] { + assert_eq!(result.get_symbols(), HashSet::from(["z".into()])); + assert_eq!( + result + .evaluate(&Some(HashMap::from([("z", 10.0)]))) + .unwrap(), + 10.0 + ); + } + } +} + +#[test] +fn substitution_preserves_formal_derivative_metadata() { + use symb_anafis::{Expr, visitor::ExprView}; + let expression = Parameter::new(Expr::derivative( + Parameter::symbol("x").sin().into_expr(), + "x", + 2, + )); + let bindings = HashMap::from([("x".into(), Parameter::symbol("y"))]); + for result in [ + expression.replace("x", Parameter::symbol("y")), + expression.substitute_many_simultaneous(&bindings), + ] { + let ExprView::Derivative { inner, var, order } = result.as_expr().view() else { + panic!("expected a formal derivative") + }; + assert_eq!(var, "x"); + assert_eq!(order, 2); + assert_eq!(inner.variables(), HashSet::from(["y".into()])); + } +} + +#[test] +fn substitution_preserves_small_and_near_unit_affine_coefficients() { + let x = Parameter::symbol("x"); + let y = Parameter::symbol("y"); + let bindings = HashMap::from([("x".into(), y.clone())]); + for coefficient in [ + 1e-16, + f64::from_bits(1), + 1.0 + f64::EPSILON, + 1.0 - f64::EPSILON, + ] { + let expression = x.clone() * coefficient; + for result in [ + expression.replace("x", y.clone()), + expression.substitute_many(&bindings), + expression.substitute_many_simultaneous(&bindings), + ] { + assert_eq!( + result.evaluate(&Some(HashMap::from([("y", 1.0)]))).unwrap(), + coefficient + ); + } + let cancelled = expression.clone() - expression; + assert_eq!( + cancelled + .substitute_many(&bindings) + .evaluate(&None) + .unwrap(), + 0.0 + ); + } +} + +#[test] +fn substitution_agrees_with_independent_numeric_composition() { + use rand::{Rng, SeedableRng, rngs::StdRng}; + fn expression(rng: &mut StdRng, depth: u32) -> Parameter { + if depth == 0 { + return Parameter::symbol(["x", "y", "z"][rng.random_range(0..3)]); + } + let lhs = expression(rng, depth - 1); + match rng.random_range(0..5) { + 0 => lhs + expression(rng, depth - 1), + 1 => lhs * expression(rng, depth - 1), + 2 => lhs.sin(), + 3 => lhs.pow(2.0), + _ => lhs / (expression(rng, depth - 1).pow(2.0) + 1.0), + } + } + let mut rng = StdRng::seed_from_u64(0xB03); + for _ in 0..64 { + let original = expression(&mut rng, 3); + let bindings = ["x", "y", "z"] + .into_iter() + .map(|name| (name.to_string(), expression(&mut rng, 1))) + .collect::>(); + let values = HashMap::from([ + ("x", rng.random_range(-0.8..0.8)), + ("y", rng.random_range(-0.8..0.8)), + ("z", rng.random_range(-0.8..0.8)), + ]); + let composed = bindings + .iter() + .map(|(name, replacement)| { + ( + name.as_str(), + replacement.evaluate(&Some(values.clone())).unwrap(), + ) + }) + .collect(); + let expected = original.evaluate(&Some(composed)).unwrap(); + for result in [ + original.substitute_many(&bindings), + original.substitute_many_simultaneous(&bindings), + ] { + let actual = result.evaluate(&Some(values.clone())).unwrap(); + assert!( + (actual - expected).abs() <= 1e-10 * expected.abs().max(1.0), + "{original}: actual={actual}, expected={expected}" + ); + } + } +} diff --git a/crates/cqlib-core/src/circuit/symbolic_matrix/gate.rs b/crates/cqlib-core/src/circuit/symbolic_matrix/gate.rs index 3cfb3983..27530d0e 100644 --- a/crates/cqlib-core/src/circuit/symbolic_matrix/gate.rs +++ b/crates/cqlib-core/src/circuit/symbolic_matrix/gate.rs @@ -155,10 +155,7 @@ pub fn standard_gate_symbolic_matrix( [o.clone(), z.clone()], [z, SymbolicComplex::exp_i(params[0].clone())] ], - StandardGate::GPhase => { - let phase = SymbolicComplex::exp_i(params[0].clone()); - ndarray::array![[phase.clone(), z.clone()], [z, phase]] - } + StandardGate::GPhase => ndarray::array![[SymbolicComplex::exp_i(params[0].clone())]], StandardGate::RXX => { let c = cos_half(¶ms[0]); let s = neg_i_times(sin_half(¶ms[0])); @@ -430,7 +427,9 @@ pub fn circuit_to_symbolic_matrix( flush_numeric_run(&mut matrix, &mut numeric_run, &full_bits)?; let matrix = matrix.get_or_insert_with(|| symbolic_eye(dim)); let base = standard_gate_symbolic_matrix(*mc_gate.base_gate(), ¶ms)?; - let gate_matrix = control_matrix(&base, mc_gate.num_ctrl_qubits()); + // The base matrix already includes any inherent controls. + let added_controls = mc_gate.num_qubits() - mc_gate.base_gate().num_qubits(); + let gate_matrix = control_matrix(&base, added_controls); apply_gate_to_matrix(matrix, &gate_matrix, &reversed_bits)?; } } @@ -546,7 +545,10 @@ pub fn circuit_to_symbolic_matrix( .circuit() .assign_parameters(&Some(bindings)) .map_err(|_| CircuitError::SymbolicParameterError)?; - let sub_matrix = circuit_to_matrix(&sub_circuit, None)?; + // Match CircuitGate argument positions to the inner storage order. + let order: Vec = + sub_circuit.qubits().iter().map(|q| q.index()).collect(); + let sub_matrix = circuit_to_matrix(&sub_circuit, Some(&order))?; push_numeric_gate( &mut matrix, &mut numeric_run, diff --git a/crates/cqlib-core/src/circuit/symbolic_matrix/gate_test.rs b/crates/cqlib-core/src/circuit/symbolic_matrix/gate_test.rs index 7d5d88ca..82fb2379 100644 --- a/crates/cqlib-core/src/circuit/symbolic_matrix/gate_test.rs +++ b/crates/cqlib-core/src/circuit/symbolic_matrix/gate_test.rs @@ -11,7 +11,7 @@ // that they have been altered from the originals. use super::*; -use crate::circuit::gate::{FrozenCircuit, UnitaryGate}; +use crate::circuit::gate::{FrozenCircuit, MCGate, UnitaryGate}; use crate::circuit::symbolic_matrix::gate::{ apply_gate_to_matrix, apply_standard_gate_to_matrix, circuit_to_symbolic_matrix, standard_gate_symbolic_matrix, @@ -36,6 +36,117 @@ fn assert_standard_gate_matches(gate: StandardGate, params: &[f64]) { assert_matrix_approx_eq(&evaluated, expected.as_ref(), 1e-10); } +#[test] +fn test_gphase_symbolic_gate_and_controls_match_scalar_formula() { + let theta = Parameter::symbol("theta"); + for controls in 0..=2 { + let base = + standard_gate_symbolic_matrix(StandardGate::GPhase, std::slice::from_ref(&theta)) + .unwrap(); + assert_eq!(base.dim(), (1, 1)); + let matrix = control_matrix(&base, controls); + let dim = 1 << controls; + assert_eq!(matrix.dim(), (dim, dim)); + for angle in [0.0, 0.37, -0.51, PI] { + let bindings = HashMap::from([("theta", angle)]); + let actual = evaluate_symbolic_matrix(&matrix, &Some(bindings)).unwrap(); + let mut expected = Array2::eye(dim); + expected[[dim - 1, dim - 1]] = Complex64::from_polar(1.0, angle); + assert_matrix_approx_eq(&actual, &expected, 1e-12); + } + } +} + +#[test] +fn test_gphase_symbolic_markers_accumulate_across_numeric_runs() { + for num_qubits in [0, 1, 3] { + let mut circuit = Circuit::new(num_qubits); + if num_qubits > 0 { + circuit.h(Qubit::new(0)).unwrap(); + } + for phase in [Parameter::from(-0.21), Parameter::symbol("theta")] { + circuit + .append( + Instruction::Standard(StandardGate::GPhase), + [] as [Qubit; 0], + [phase.into()], + None, + ) + .unwrap(); + } + if num_qubits > 0 { + circuit + .rz(Qubit::new(0), Parameter::symbol("alpha")) + .unwrap(); + } + circuit + .append( + Instruction::Standard(StandardGate::GPhase), + [] as [Qubit; 0], + [0.12.into()], + None, + ) + .unwrap(); + circuit.set_global_phase(Parameter::from(0.17)); + let symbolic = circuit_to_symbolic_matrix(&circuit, None).unwrap(); + let mut baseline = Circuit::new(num_qubits); + if num_qubits > 0 { + baseline.h(Qubit::new(0)).unwrap(); + baseline.rz(Qubit::new(0), Parameter::from(0.23)).unwrap(); + } + let baseline = circuit_to_matrix(&baseline, None).unwrap(); + for theta in [0.0, 0.37, -0.51, PI] { + let bindings = HashMap::from([("theta", theta), ("alpha", 0.23)]); + let actual = evaluate_symbolic_matrix(&symbolic, &Some(bindings)).unwrap(); + let expected = &baseline * Complex64::from_polar(1.0, theta - 0.21 + 0.12 + 0.17); + assert_matrix_approx_eq(&actual, &expected, 1e-12); + } + } +} + +#[test] +fn test_gphase_symbolic_controlled_circuit_with_constant_and_symbolic_params() { + for controls in [vec![], vec![2usize], vec![2, 0]] { + for phase in [Parameter::from(0.37), Parameter::symbol("theta")] { + let mut circuit = Circuit::new(3); + circuit.h(Qubit::new(1)).unwrap(); + circuit + .multi_control( + StandardGate::GPhase, + controls.iter().map(|&q| Qubit::new(q as u32)), + [] as [Qubit; 0], + [phase.into()], + ) + .unwrap(); + for order in [[0, 1, 2], [2, 0, 1]] { + let spectator_bit = order.iter().position(|&q| q == 1).unwrap(); + let mask = controls.iter().fold(0, |mask, control| { + mask | (1 << order.iter().position(|q| q == control).unwrap()) + }); + let symbolic = circuit_to_symbolic_matrix(&circuit, Some(&order)).unwrap(); + let bindings = HashMap::from([("theta", 0.37)]); + let actual = evaluate_symbolic_matrix(&symbolic, &Some(bindings)).unwrap(); + let mut expected = Array2::zeros((8, 8)); + for row in 0..8 { + for col in 0..8 { + if (row ^ col) & !(1 << spectator_bit) == 0 { + let sign = if row & col & (1 << spectator_bit) != 0 { + -1.0 + } else { + 1.0 + }; + let angle = if row & mask == mask { 0.37 } else { 0.0 }; + expected[[row, col]] = + Complex64::from_polar(1.0, angle) * sign / std::f64::consts::SQRT_2; + } + } + } + assert_matrix_approx_eq(&actual, &expected, 1e-12); + } + } + } +} + #[test] fn test_fixed_standard_gate_matches_numeric_matrix() { let symbolic = standard_gate_symbolic_matrix(StandardGate::H, &[]).unwrap(); @@ -795,6 +906,202 @@ fn test_substitution_cross_dependency() { assert_matrix_approx_eq(&evaluated, expected.as_ref(), 1e-10); } +#[test] +fn test_circuit_gate_storage_order_constant_symbolic_matrix() { + for order in [[7, 2], [1, 0], [2, 7], [0, 1]] { + let order = order.map(Qubit::new); + let mut inner = Circuit::from_qubits(order.to_vec()).unwrap(); + inner.x(order[0]).unwrap(); + let gate = inner.to_gate("StoredOrderX").unwrap(); + for targets in [[4, 9], [9, 4]] { + let targets = targets.map(Qubit::new); + let mut circuit = Circuit::from_qubits(vec![Qubit::new(9), Qubit::new(4)]).unwrap(); + circuit.append(gate.clone(), targets, [], None).unwrap(); + let mut expected = Circuit::from_qubits(vec![Qubit::new(9), Qubit::new(4)]).unwrap(); + expected.x(targets[0]).unwrap(); + for output_order in [None, Some([9, 4].as_slice())] { + let symbolic = circuit_to_symbolic_matrix(&circuit, output_order).unwrap(); + let evaluated = evaluate_symbolic_matrix(&symbolic, &None).unwrap(); + assert_matrix_approx_eq( + &evaluated, + &circuit_to_matrix(&expected, output_order).unwrap(), + 1e-10, + ); + } + } + } +} + +#[test] +fn test_circuit_gate_storage_order_nested_parameterized_inverse() { + for middle_order in [None, Some([0, 1]), Some([5, 1])] { + let mut body = Circuit::from_qubits(vec![Qubit::new(7), Qubit::new(2)]).unwrap(); + body.rx(Qubit::new(7), Parameter::symbol("theta")).unwrap(); + body.cx(Qubit::new(7), Qubit::new(2)).unwrap(); + if let Some(order) = middle_order { + let gate = body.to_gate("Inner").unwrap(); + body = Circuit::from_qubits(order.map(Qubit::new).to_vec()).unwrap(); + body.append( + gate, + order.map(Qubit::new), + [ParameterValue::from(Parameter::symbol("theta"))], + None, + ) + .unwrap(); + } + let mut outer = Circuit::new(2); + outer + .append( + body.to_gate("Body").unwrap(), + [Qubit::new(0), Qubit::new(1)], + [ParameterValue::from(Parameter::symbol("x"))], + None, + ) + .unwrap(); + for inverse in [false, true] { + let circuit = if inverse { + outer.inverse().unwrap() + } else { + outer.clone() + }; + let symbolic = circuit_to_symbolic_matrix(&circuit, None).unwrap(); + for angle in [0.37, -0.61] { + let bindings = Some(HashMap::from([("x", angle)])); + let bound = circuit.assign_parameters(&bindings).unwrap(); + let mut expected = Circuit::new(2); + expected.rx(Qubit::new(0), angle).unwrap(); + expected.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + if inverse { + expected = expected.inverse().unwrap(); + } + let expected_matrix = circuit_to_matrix(&expected, None).unwrap(); + assert_matrix_approx_eq( + &evaluate_symbolic_matrix(&symbolic, &bindings).unwrap(), + &expected_matrix, + 1e-10, + ); + assert_matrix_approx_eq( + &circuit_to_matrix(&bound, None).unwrap(), + &expected_matrix, + 1e-10, + ); + assert_matrix_approx_eq( + &circuit_to_matrix(&bound.decompose().unwrap(), None).unwrap(), + &expected_matrix, + 1e-10, + ); + } + } + } +} + +#[test] +fn test_circuit_gate_storage_order_cache_isolation() { + use crate::circuit::gate::CircuitGate; + + let mut inner = Circuit::from_qubits(vec![Qubit::new(7), Qubit::new(2)]).unwrap(); + inner.rx(Qubit::new(7), Parameter::symbol("theta")).unwrap(); + inner.cx(Qubit::new(7), Qubit::new(2)).unwrap(); + let frozen = FrozenCircuit::new(inner.clone()); + let gate = CircuitGate::new("Cached", frozen.clone()).unwrap(); + // Materializing either cache first must not determine the other's basis. + for gate_first in [false, true] { + let frozen = if gate_first { + FrozenCircuit::new(inner.clone()) + } else { + frozen.clone() + }; + let gate = if gate_first { + CircuitGate::new("Cached", frozen.clone()).unwrap() + } else { + gate.clone() + }; + if gate_first { + gate.symbolic_matrix().unwrap(); + } else { + frozen.symbolic_matrix().unwrap(); + } + let gate_matrix = gate.symbolic_matrix().unwrap(); + assert!(Arc::ptr_eq( + &gate_matrix, + &gate.clone().symbolic_matrix().unwrap() + )); + assert_eq!(frozen, FrozenCircuit::new(inner.clone())); + let bindings = Some(HashMap::from([("theta", 0.37)])); + let assigned = inner.assign_parameters(&bindings).unwrap(); + assert_matrix_approx_eq( + &evaluate_symbolic_matrix(&gate_matrix, &bindings).unwrap(), + &circuit_to_matrix(&assigned, Some(&[7, 2])).unwrap(), + 1e-10, + ); + let default_matrix = frozen.symbolic_matrix().unwrap(); + assert!(Arc::ptr_eq( + &default_matrix, + &frozen.symbolic_matrix().unwrap() + )); + assert_matrix_approx_eq( + &evaluate_symbolic_matrix(&default_matrix, &bindings).unwrap(), + &circuit_to_matrix(&assigned, None).unwrap(), + 1e-10, + ); + // Circuit-backed UnitaryGate keeps its existing numeric-sorted basis. + let unitary = UnitaryGate::new("Frozen", 2, 1) + .with_circuit(Arc::new(frozen)) + .unwrap(); + let mut unitary_circuit = Circuit::new(2); + unitary_circuit + .append( + Instruction::UnitaryGate(Box::new(unitary)), + [Qubit::new(0), Qubit::new(1)], + [ParameterValue::from(Parameter::symbol("x"))], + None, + ) + .unwrap(); + let mut unitary_expected = Circuit::new(2); + unitary_expected.rx(Qubit::new(1), 0.37).unwrap(); + unitary_expected.cx(Qubit::new(1), Qubit::new(0)).unwrap(); + let bindings = Some(HashMap::from([("x", 0.37)])); + let expected = circuit_to_matrix(&unitary_expected, None).unwrap(); + assert_matrix_approx_eq( + &evaluate_symbolic_matrix( + &circuit_to_symbolic_matrix(&unitary_circuit, None).unwrap(), + &bindings, + ) + .unwrap(), + &expected, + 1e-10, + ); + assert_matrix_approx_eq( + &circuit_to_matrix(&unitary_circuit.assign_parameters(&bindings).unwrap(), None) + .unwrap(), + &expected, + 1e-10, + ); + let mut circuit = Circuit::new(2); + let mut expected = Circuit::new(2); + for (targets, scale) in [([0, 1], 1.0), ([1, 0], 2.0)] { + circuit + .append( + Instruction::CircuitGate(Box::new(gate.clone())), + targets.map(Qubit::new), + [ParameterValue::from(Parameter::symbol("x") * scale)], + None, + ) + .unwrap(); + expected.rx(Qubit::new(targets[0]), 0.37 * scale).unwrap(); + expected + .cx(Qubit::new(targets[0]), Qubit::new(targets[1])) + .unwrap(); + } + let symbolic = circuit_to_symbolic_matrix(&circuit, None).unwrap(); + assert_matrix_approx_eq( + &evaluate_symbolic_matrix(&symbolic, &bindings).unwrap(), + &circuit_to_matrix(&expected, None).unwrap(), + 1e-10, + ); + } +} + #[test] fn test_frozen_circuit_symbolic_matrix_cache_reuses_arc() { let mut inner = Circuit::new(1); @@ -1175,6 +1482,82 @@ fn test_mcgate_parametric_symbolic_matrix_matches_numeric() { assert_matrix_approx_eq(&evaluated, &expected, 1e-10); } +#[test] +fn test_mcgate_zero_added_controls_preserves_symbolic_controlled_rotations() { + for gate in [StandardGate::CRX, StandardGate::CRY, StandardGate::CRZ] { + let mut circuit = Circuit::new(2); + circuit + .append( + Instruction::McGate(Box::new(MCGate::new(0, gate))), + [Qubit::new(0), Qubit::new(1)], + [ParameterValue::from(Parameter::symbol("theta"))], + None, + ) + .unwrap(); + let symbolic = circuit_to_symbolic_matrix(&circuit, Some(&[1, 0])).unwrap(); + assert_eq!(symbolic.dim(), (4, 4)); + for theta in [0.0, 0.37, -0.51, PI] { + let bindings = HashMap::from([("theta", theta)]); + let actual = evaluate_symbolic_matrix(&symbolic, &Some(bindings)).unwrap(); + let expected = gate.matrix(&[theta]).unwrap(); + assert_matrix_approx_eq(&actual, expected.as_ref(), 1e-12); + } + } +} + +#[test] +fn test_mcgate_inherent_controls_symbolic_matrix_matches_bound_numeric() { + for gate in [StandardGate::CRX, StandardGate::CRY, StandardGate::CRZ] { + for added_controls in 0..=2 { + let mc_gate = MCGate::new(added_controls, gate); + assert_eq!(mc_gate.num_ctrl_qubits(), added_controls as usize + 1); + let num_qubits = mc_gate.num_qubits() + 1; + let qubit_ids = [9usize, 2, 17, 5, 30][..num_qubits].to_vec(); + let qubits: Vec = qubit_ids.iter().map(|&id| Qubit::new(id as u32)).collect(); + // Leave a spectator between gate operands in the circuit's stored order. + let operands: Vec = qubits + .iter() + .enumerate() + .filter_map(|(index, &qubit)| (index != 1).then_some(qubit)) + .collect(); + for reverse in [false, true] { + let mut operands = operands.clone(); + if reverse { + operands.reverse(); + } + let mut circuit = Circuit::from_qubits(qubits.clone()).unwrap(); + circuit.h(operands[0]).unwrap(); + circuit.x(qubits[1]).unwrap(); + circuit + .append( + Instruction::McGate(Box::new(mc_gate.clone())), + operands.clone(), + [ParameterValue::from(Parameter::symbol("theta"))], + None, + ) + .unwrap(); + circuit.rz(*operands.last().unwrap(), 0.23).unwrap(); + for order in [None, Some(qubit_ids.as_slice())] { + let symbolic = circuit_to_symbolic_matrix(&circuit, order).unwrap(); + let dim = 1 << num_qubits; + assert_eq!(symbolic.dim(), (dim, dim)); + for theta in [0.0, 0.37, -0.51, PI] { + let bindings = HashMap::from([("theta", theta)]); + let actual = + evaluate_symbolic_matrix(&symbolic, &Some(bindings.clone())).unwrap(); + let bound = circuit.assign_parameters(&Some(bindings)).unwrap(); + let expected = circuit_to_matrix(&bound, order).unwrap(); + assert_matrix_approx_eq(&actual, &expected, 1e-12); + let constant_symbolic = circuit_to_symbolic_matrix(&bound, order).unwrap(); + let constant = evaluate_symbolic_matrix(&constant_symbolic, &None).unwrap(); + assert_matrix_approx_eq(&constant, &expected, 1e-12); + } + } + } + } + } +} + #[test] fn test_numeric_path_matches_symbolic_path_for_no_param_gates() { // H, CX, X2P — all non-parametric gates should take the numeric fast path diff --git a/crates/cqlib-core/src/circuit/value_instruction.rs b/crates/cqlib-core/src/circuit/value_instruction.rs index e57d5b17..5cb8fd9c 100644 --- a/crates/cqlib-core/src/circuit/value_instruction.rs +++ b/crates/cqlib-core/src/circuit/value_instruction.rs @@ -47,9 +47,11 @@ use crate::circuit::classical::{ClassicalValue, ClassicalVar}; use crate::circuit::classical_expr::ClassicalExpr; use crate::circuit::control_flow::{ControlBody, validate_for_types, validate_switch}; use crate::circuit::error::CircuitError; +use crate::circuit::gate::circuit_gate::CircuitGate; use crate::circuit::gate::directive::Directive; use crate::circuit::gate::instruction::Instruction; use crate::circuit::gate::standard_gate::StandardGate; +use crate::circuit::gate::{ClassicalDataOp, MCGate, UnitaryGate}; use crate::circuit::operation::{Operation, ValueOperation}; use alloc::collections::BTreeSet; use std::fmt; @@ -551,17 +553,40 @@ impl ValueInstruction { /// Returns the standard gate when this is a standard-gate instruction. pub fn standard_gate(&self) -> Option { - match self { - Self::Instruction(Instruction::Standard(gate)) => Some(*gate), - _ => None, - } + self.as_instruction().and_then(Instruction::standard_gate) } /// Returns the directive when this is a directive instruction. pub fn directive(&self) -> Option { + self.as_instruction().and_then(Instruction::directive) + } + + /// Returns the multi-controlled gate when this is an mc-gate instruction. + pub fn mc_gate(&self) -> Option<&MCGate> { + self.as_instruction().and_then(Instruction::mc_gate) + } + + /// Returns the user-defined unitary gate when this is a unitary instruction. + pub fn unitary_gate(&self) -> Option<&UnitaryGate> { + self.as_instruction().and_then(Instruction::unitary_gate) + } + + /// Returns the circuit-backed gate when this is a circuit-gate instruction. + pub fn circuit_gate(&self) -> Option<&CircuitGate> { + self.as_instruction().and_then(Instruction::circuit_gate) + } + + /// Returns the classical data operation when this is a classical-data instruction. + pub fn classical_data(&self) -> Option<&ClassicalDataOp> { + self.as_instruction().and_then(Instruction::classical_data) + } + + /// Returns the value-level control-flow operation when this is a classical + /// control-flow instruction. + pub fn classical_control(&self) -> Option<&ValueClassicalControlOp> { match self { - Self::Instruction(Instruction::Directive(directive)) => Some(*directive), - _ => None, + Self::Instruction(_) => None, + Self::ClassicalControl(op) => Some(op), } } @@ -789,6 +814,64 @@ mod tests { assert!(delay.is_delay()); } + #[test] + fn value_instruction_delegates_payload_accessors() { + let mc = ValueInstruction::from_instruction(Instruction::McGate(Box::new(MCGate::new( + 2, + StandardGate::X, + )))); + assert!(mc.is_mcgate()); + let mc_gate = mc.mc_gate().unwrap(); + assert_eq!(mc_gate.num_ctrl_qubits(), 2); + assert_eq!(mc_gate.base_gate(), &StandardGate::X); + assert!(mc.unitary_gate().is_none()); + assert!(mc.circuit_gate().is_none()); + assert!(mc.classical_data().is_none()); + + let unitary = ValueInstruction::from_instruction(Instruction::UnitaryGate(Box::new( + UnitaryGate::new("oracle", 1, 0), + ))); + assert!(unitary.is_unitary()); + assert_eq!( + unitary.unitary_gate().map(|gate| gate.label()), + Some("oracle") + ); + assert!(unitary.mc_gate().is_none()); + + let circuit_gate = CircuitGate::new( + "composite", + crate::circuit::gate::circuit_gate::FrozenCircuit::new(crate::circuit::Circuit::new(1)), + ) + .unwrap(); + let circuit = + ValueInstruction::from_instruction(Instruction::CircuitGate(Box::new(circuit_gate))); + assert_eq!( + circuit.circuit_gate().map(|gate| gate.name()), + Some("composite") + ); + + let value = + ClassicalValue::new(crate::circuit::CircuitId::default(), 0, ClassicalType::Bit); + let data = ValueInstruction::from_instruction(Instruction::ClassicalData( + ClassicalDataOp::MeasureBit { result: value }, + )); + assert_eq!( + data.classical_data().and_then(|op| op.result()), + Some(value) + ); + + let control = ValueInstruction::from(ValueClassicalControlOp::Break); + assert!(control.mc_gate().is_none()); + assert!(control.unitary_gate().is_none()); + assert!(control.circuit_gate().is_none()); + assert!(control.classical_data().is_none()); + assert_eq!( + control.classical_control(), + Some(&ValueClassicalControlOp::Break) + ); + assert!(data.classical_control().is_none()); + } + #[test] fn value_classical_control_reads_and_writes() { let var = ClassicalVar::new( diff --git a/crates/cqlib-core/src/compile/commutation/commutation_test.rs b/crates/cqlib-core/src/compile/commutation/commutation_test.rs index 15deebd2..4cea713b 100644 --- a/crates/cqlib-core/src/compile/commutation/commutation_test.rs +++ b/crates/cqlib-core/src/compile/commutation/commutation_test.rs @@ -80,6 +80,215 @@ fn assert_pi_phase(result: CommutationResult) { assert!((phase.evaluate(&None).unwrap() - PI).abs() < 1e-10); } +#[test] +fn circuit_backed_unitary_matrix_fallback_respects_targets_and_parameters() { + for order in [vec![0, 1], vec![1, 0], vec![7, 2], vec![9, 2, 7]] { + let mut numeric_order = order.clone(); + numeric_order.sort_unstable(); + let qubits: Vec = [5, 1, 8][..order.len()] + .iter() + .copied() + .map(Qubit::new) + .collect(); + for active in 0..order.len() { + for parameterized in [false, true] { + let mut body = + Circuit::from_qubits(order.iter().copied().map(Qubit::new).collect()).unwrap(); + body.rx( + Qubit::new(numeric_order[active]), + if parameterized { + Parameter::symbol("theta") + } else { + Parameter::from(0.7) + }, + ) + .unwrap(); + body.set_global_phase(Parameter::from(0.19)); + let instruction = Instruction::UnitaryGate(Box::new( + UnitaryGate::new("rx_one_port", order.len() as u16, u16::from(parameterized)) + .with_circuit(std::sync::Arc::new(FrozenCircuit::new(body))) + .unwrap(), + )); + let params = if parameterized { + vec![Parameter::from(0.7)] + } else { + vec![] + }; + let z = Instruction::Standard(StandardGate::Z); + for checker in [ + CommutationChecker::builtin(), + CommutationChecker::with_config(CommutationConfig { + enable_rule_oracle: false, + ..CommutationConfig::default() + }), + ] { + for (position, &qubit) in qubits.iter().enumerate() { + for result in [ + checker.check(&instruction, &qubits, ¶ms, &z, &[qubit], &[]), + checker.check(&z, &[qubit], &[], &instruction, &qubits, ¶ms), + ] { + if position == active { + assert!(result.is_none(), "order={order:?}, active={active}"); + } else { + assert_exact(result); + } + } + } + } + if parameterized { + assert!( + super::matrix::matrix_commutation( + &instruction, + &qubits, + &[Parameter::symbol("unresolved")], + &z, + &[qubits[active]], + &[], + 4, + ) + .is_none() + ); + } + assert!( + super::matrix::matrix_commutation( + &instruction, + &qubits, + ¶ms, + &z, + &[qubits[active]], + &[], + order.len() - 1, + ) + .is_none() + ); + } + } + } +} + +#[test] +fn circuit_backed_unitary_matrix_fallback_preserves_global_phase_proof() { + let mut body = Circuit::new(2); + body.x(Qubit::new(0)).unwrap(); + body.set_global_phase(Parameter::from(0.19)); + let instruction = Instruction::UnitaryGate(Box::new( + UnitaryGate::new("x_first", 2, 0) + .with_circuit(std::sync::Arc::new(FrozenCircuit::new(body))) + .unwrap(), + )); + let qubits = [Qubit::new(5), Qubit::new(1)]; + let z = Instruction::Standard(StandardGate::Z); + let checker = CommutationChecker::builtin(); + assert_pi_phase(checker.check(&instruction, &qubits, &[], &z, &[qubits[0]], &[])); + assert_pi_phase(checker.check(&z, &[qubits[0]], &[], &instruction, &qubits, &[])); + assert_exact(checker.check(&instruction, &qubits, &[], &z, &[qubits[1]], &[])); +} + +#[test] +fn circuit_gate_operation_matrix_does_not_certify_false_commutation() { + let mut body = Circuit::new(2); + body.rx(Qubit::new(0), Parameter::from(0.37)).unwrap(); + let instruction = body.to_gate("rx_first").unwrap(); + let qubits = [Qubit::new(0), Qubit::new(1)]; + let checker = CommutationChecker::with_config(CommutationConfig { + enable_rule_oracle: false, + ..CommutationConfig::default() + }); + assert!( + checker + .check( + &instruction, + &qubits, + &[], + &Instruction::Standard(StandardGate::Z), + &[qubits[0]], + &[], + ) + .is_none() + ); +} + +#[test] +fn circuit_gate_matrix_fallback_respects_targets_parameters_and_phase() { + for order in [[0, 1], [1, 0], [7, 2]] { + for parameterized in [false, true] { + let mut body = Circuit::from_qubits(order.map(Qubit::new).to_vec()).unwrap(); + body.rx( + Qubit::new(order[0]), + if parameterized { + Parameter::symbol("theta") + } else { + Parameter::from(0.37) + }, + ) + .unwrap(); + let instruction = body.to_gate("rx_first").unwrap(); + let params = if parameterized { + vec![Parameter::from(0.37)] + } else { + vec![] + }; + let qubits = [Qubit::new(5), Qubit::new(1)]; + for checker in [ + CommutationChecker::builtin(), + CommutationChecker::with_config(CommutationConfig { + enable_rule_oracle: false, + ..CommutationConfig::default() + }), + ] { + for (position, &qubit) in qubits.iter().enumerate() { + let z = Instruction::Standard(StandardGate::Z); + for result in [ + checker.check(&instruction, &qubits, ¶ms, &z, &[qubit], &[]), + checker.check(&z, &[qubit], &[], &instruction, &qubits, ¶ms), + ] { + if position == 0 { + assert!(result.is_none()); + } else { + assert_exact(result); + } + } + } + } + if parameterized { + assert!( + super::matrix::matrix_commutation( + &instruction, + &qubits, + &[Parameter::symbol("unresolved")], + &Instruction::Standard(StandardGate::Z), + &[qubits[0]], + &[], + 4, + ) + .is_none() + ); + } + } + } + let mut body = Circuit::new(2); + body.x(Qubit::new(0)).unwrap(); + let x = body.to_gate("x_first").unwrap(); + let z = Instruction::Standard(StandardGate::Z); + let checker = CommutationChecker::builtin(); + assert_pi_phase(checker.check( + &x, + &[Qubit::new(0), Qubit::new(1)], + &[], + &z, + &[Qubit::new(0)], + &[], + )); + assert_pi_phase(checker.check( + &z, + &[Qubit::new(0)], + &[], + &x, + &[Qubit::new(0), Qubit::new(1)], + &[], + )); +} + #[test] fn identity_commutes_exactly() { let checker = CommutationChecker::builtin(); diff --git a/crates/cqlib-core/src/compile/commutation/matrix.rs b/crates/cqlib-core/src/compile/commutation/matrix.rs index 448d896e..c50bd939 100644 --- a/crates/cqlib-core/src/compile/commutation/matrix.rs +++ b/crates/cqlib-core/src/compile/commutation/matrix.rs @@ -101,7 +101,7 @@ pub fn matrix_commutation( /// /// `gate_positions` maps each gate-local qubit to its position in the sorted /// combined support used by [`matrix_commutation`]. Bit extraction follows the -/// existing circuit matrix convention: earlier qubits correspond to more +/// gate-local matrix convention: earlier qubits correspond to more /// significant bits in the local basis index. fn expand_unitary( matrix: Cow<'_, Array2>, diff --git a/crates/cqlib-core/src/compile/device_planning/planner_test.rs b/crates/cqlib-core/src/compile/device_planning/planner_test.rs index 284a459b..3e8a8e3f 100644 --- a/crates/cqlib-core/src/compile/device_planning/planner_test.rs +++ b/crates/cqlib-core/src/compile/device_planning/planner_test.rs @@ -568,3 +568,82 @@ fn direction_template_preserves_exact_ordered_qargs() { &[PhysicalQubit::new(1)] ); } + +#[test] +fn single_qubit_rule_expansion_stays_bounded_with_heterogeneous_calibrations() { + use StandardGate::*; + let library = RuleLibrary::builtin_rules().unwrap(); + for basis in [ + vec![U, CZ], + vec![U, CX], + vec![RY, RZ, CX], + vec![RY, RZ, CZ], + vec![RXY, CX], + vec![RZ, X2P, CZ], + vec![RZ, X2M, CX], + vec![RZ, Y2P, CX], + vec![RZ, Y2M, CZ], + vec![RZ, XY2P, CZ], + vec![RZ, XY2M, CX], + ] { + for profile in 0..4 { + let mut device = Device::bidirectional_line("single-qubit-expansion-budget", 2) + .unwrap() + .with_native_gates(basis.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + for (q, (error, duration)) in [(0, (0.001, 84.0)), (1, (0.006, 45.0))] { + let mut properties = QubitProp::new(0.0); + for &gate in basis.iter().filter(|gate| gate.num_qubits() == 1) { + let scale = 1.0 + profile as f64; + let mut native = + InstructionProp::new(Instruction::Standard(gate), error * scale); + if profile != 3 { + native = native.with_length(duration / scale); + } + properties = properties.with_native_instruction(native).unwrap(); + } + device + .add_qubit_properties(PhysicalQubit::new(q), properties) + .unwrap(); + } + for (a, b, error, duration) in [(0, 1, 0.019, 59.0), (1, 0, 0.016, 293.0)] { + let mut native = + InstructionProp::new(Instruction::Standard(*basis.last().unwrap()), error); + if profile != 2 { + native = native.with_length(duration * (1.0 + profile as f64)); + } + device + .add_edge_properties( + PhysicalQubit::new(a), + PhysicalQubit::new(b), + EdgeProp::new().with_native_instruction(native).unwrap(), + ) + .unwrap(); + } + let roots = [state(SWAP, &[0, 1]), state(SWAP, &[1, 0])]; + let planner = build_planner_with_budget( + &device, + library, + roots.clone(), + PlannerBudget { + max_frontier_size_per_state: 32, + max_total_plan_nodes: 5_000, + max_total_generated_candidates: 20_000, + }, + ) + .unwrap_or_else(|error| panic!("{basis:?}, profile={profile}: {error}")); + for root in roots { + assert!( + planner.selected_plan_for(&root).is_some(), + "{basis:?}: {root:?}" + ); + } + eprintln!( + "basis={basis:?}, profile={profile}, nodes={}, candidates={}, frontier={}", + planner.nodes.len(), + planner.generated_candidates, + planner.frontiers.iter().map(Vec::len).max().unwrap_or(0) + ); + } + } +} diff --git a/crates/cqlib-core/src/compile/knowledge/builtin_rules_contract_test.rs b/crates/cqlib-core/src/compile/knowledge/builtin_rules_contract_test.rs index 619f7a78..e02a04f6 100644 --- a/crates/cqlib-core/src/compile/knowledge/builtin_rules_contract_test.rs +++ b/crates/cqlib-core/src/compile/knowledge/builtin_rules_contract_test.rs @@ -903,8 +903,8 @@ fn decompose_swap_x2p_cz_triple_product_differs_from_swap_by_exactly_pi() { "bare (X2P⊗X2P)·CZ triple product must differ from SWAP by a global phase" ); - // The qiskit SX-convention tail -π/2 is wrong for the phase-free X2P - // convention used here: it yields exp(iπ/2)·SWAP = i·SWAP. + // With X2P = Rx(π/2), a phase tail of -π/2 yields + // exp(iπ/2)·SWAP = i·SWAP instead of exactly SWAP. let mut wrong_phase = repeat_three_times(|c| { c.x2p(q0).unwrap(); c.x2p(q1).unwrap(); diff --git a/crates/cqlib-core/src/compile/knowledge/matcher_test.rs b/crates/cqlib-core/src/compile/knowledge/matcher_test.rs index ead1817e..ee37c6da 100644 --- a/crates/cqlib-core/src/compile/knowledge/matcher_test.rs +++ b/crates/cqlib-core/src/compile/knowledge/matcher_test.rs @@ -319,6 +319,56 @@ fn instantiate_target_rejects_unbound_rewrite_references() { ); } +#[test] +fn instantiate_target_substitutes_overlapping_symbol_names_simultaneously() { + let a = Parameter::symbol("a"); + let b = Parameter::symbol("b"); + let rule = Rule::new( + "overlapping_parameters", + vec![ + RuleItem::standard( + StandardGate::RZ, + &[0], + vec![ParameterValue::Param(a.clone())], + ), + RuleItem::standard( + StandardGate::RZ, + &[0], + vec![ParameterValue::Param(b.clone())], + ), + ], + vec![RuleItem::standard( + StandardGate::RZ, + &[0], + vec![ParameterValue::Param(a.clone() + b.clone() * 2.0)], + )], + ); + let instruction = Instruction::Standard(StandardGate::RZ); + let qubits = [Qubit::new(0)]; + let first = [b]; + let second = [a]; + let operations = [ + ConcreteOperationView::new(&instruction, &qubits, &first), + ConcreteOperationView::new(&instruction, &qubits, &second), + ]; + let bindings = rule_matches_operations(&rule, &operations) + .unwrap() + .unwrap(); + let replacements = instantiate_target(&rule.target, &bindings).unwrap(); + let ParameterValue::Param(result) = &replacements[0].params[0] else { + panic!("expected a symbolic parameter"); + }; + assert_eq!( + result + .evaluate(&Some(std::collections::HashMap::from([ + ("a", 1.0), + ("b", 3.0) + ]))) + .unwrap(), + 5.0 + ); +} + #[test] fn rule_matches_operations_returns_none_for_non_adjacent_policy_cases() { let rule = Rule::new( diff --git a/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs b/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs index 2f5e7333..ea4c748c 100644 --- a/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs +++ b/crates/cqlib-core/src/compile/knowledge/rule_equivalence_test.rs @@ -425,3 +425,74 @@ fn qcis_fsim_to_cz_verify_timing() { fn verify_all_builtin_rules_layered_equivalence_ignored() { verify_all_builtin_rules_layered_equivalence(); } + +/// Check registered DSL rules, including independent random parameters and all +/// scalar phases. A copied formula test would not catch an incorrect DSL edit. +#[test] +fn native_single_qubit_paths_preserve_full_unitary_for_parameters() { + use crate::circuit::circuit_to_matrix::circuit_to_matrix; + use rand::{Rng, SeedableRng, rngs::SmallRng}; + + let library = RuleLibrary::builtin_rules().unwrap(); + let mut rng = SmallRng::seed_from_u64(20261021); + for name in [ + "decompose_h_to_u", + "decompose_rx_to_u", + "decompose_ry_to_u", + "decompose_rxy_to_u", + "decompose_rx_to_rxy", + "decompose_ry_to_rxy", + "decompose_xy2p_to_xy2m", + "decompose_u_to_x2p_rz_same_sign", + "decompose_u_to_x2m_rz_same_sign", + "decompose_u_to_y2p_rz_same_sign", + "decompose_u_to_y2m_rz_same_sign", + ] { + let rule = library + .get_by_name(name) + .expect("native rule must be registered"); + let lhs = rule_items_to_circuit(&rule.operations, rule.num_qubits()).unwrap(); + let rhs = rule_items_to_circuit(&rule.target, rule.num_qubits()).unwrap(); + let mut symbols: Vec<_> = rule.collect_free_symbols().into_iter().collect(); + symbols.sort(); + for sample in 0..112 { + let bindings = Some( + symbols + .iter() + .enumerate() + .map(|(index, name)| { + let edge = [ + 0.0, + std::f64::consts::FRAC_PI_2, + -std::f64::consts::FRAC_PI_2, + std::f64::consts::PI, + -std::f64::consts::PI, + 2.0 * std::f64::consts::PI, + -2.0 * std::f64::consts::PI, + 4.0 * std::f64::consts::PI, + -4.0 * std::f64::consts::PI, + 1e-12, + -1e-12, + 0.173, + ]; + ( + name.as_str(), + if sample < edge.len() { + edge[(sample + index * 3) % edge.len()] + } else { + rng.random_range(-20.0..20.0) + }, + ) + }) + .collect(), + ); + let a = circuit_to_matrix(&lhs.assign_parameters(&bindings).unwrap(), None).unwrap(); + let b = circuit_to_matrix(&rhs.assign_parameters(&bindings).unwrap(), None).unwrap(); + let error = max_diff_strict(&a, &b); + assert!( + error < 1e-10, + "{name}: strict error {error}, bindings={bindings:?}" + ); + } + } +} diff --git a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule index 0e48f5bf..32839b20 100644 --- a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule +++ b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_clifford.rule @@ -168,3 +168,8 @@ rule decompose_y2m_to_x2m { match { Y2M 0 } rewrite { RZ(-π/2) 0, X2M 0, RZ(π/2) 0 } } + +rule decompose_h_to_u { + match { H 0 } + rewrite { U(π/2, 0, π) 0 } +} diff --git a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule index a0a29325..8437c47b 100644 --- a/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule +++ b/crates/cqlib-core/src/compile/knowledge/rules/decompose_single_rotation.rule @@ -168,3 +168,53 @@ rule decompose_u_to_xy_basis { match { U(theta, phi, lambda) 0 } rewrite { RZ(lambda) 0, XY2P(0) 0, RZ(theta) 0, XY2M(0) 0, RZ(phi) 0, GPhase((phi + lambda) / 2) } } + +rule decompose_rx_to_u { + match { RX(theta) 0 } + rewrite { U(theta, -π/2, π/2) 0 } +} + +rule decompose_ry_to_u { + match { RY(theta) 0 } + rewrite { U(theta, 0, 0) 0 } +} + +rule decompose_rxy_to_u { + match { RXY(theta, phi) 0 } + rewrite { U(theta, phi - π/2, π/2 - phi) 0 } +} + +rule decompose_rx_to_rxy { + match { RX(theta) 0 } + rewrite { RXY(theta, 0) 0 } +} + +rule decompose_ry_to_rxy { + match { RY(theta) 0 } + rewrite { RXY(theta, π/2) 0 } +} + +rule decompose_xy2p_to_xy2m { + match { XY2P(phi) 0 } + rewrite { XY2M(phi + π) 0 } +} + +rule decompose_u_to_x2p_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda) 0, X2P 0, RZ(theta + π) 0, X2P 0, RZ(phi + π) 0, GPhase((phi + lambda) / 2 + π) } +} + +rule decompose_u_to_x2m_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda) 0, X2M 0, RZ(π - theta) 0, X2M 0, RZ(phi + π) 0, GPhase((phi + lambda) / 2 + π) } +} + +rule decompose_u_to_y2p_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda + π/2) 0, Y2P 0, RZ(theta + π) 0, Y2P 0, RZ(phi + π/2) 0, GPhase((phi + lambda) / 2 + π) } +} + +rule decompose_u_to_y2m_rz_same_sign { + match { U(theta, phi, lambda) 0 } + rewrite { RZ(lambda + π/2) 0, Y2M 0, RZ(π - theta) 0, Y2M 0, RZ(phi + π/2) 0, GPhase((phi + lambda) / 2 + π) } +} diff --git a/crates/cqlib-core/src/compile/test_utils.rs b/crates/cqlib-core/src/compile/test_utils.rs index 295a0cbd..d112da1e 100644 --- a/crates/cqlib-core/src/compile/test_utils.rs +++ b/crates/cqlib-core/src/compile/test_utils.rs @@ -25,6 +25,38 @@ use std::sync::Arc; const EPSILON: f64 = 1e-9; +/// The reported unitary whose Cartan coordinates lie on the a=pi/4 wall. +pub(crate) fn kak_boundary_matrix() -> ndarray::Array2 { + use num_complex::Complex64; + + ndarray::array![ + [ + Complex64::new(-0.14755155196621783, 0.08535345227001921), + Complex64::new(-0.015112015359785388, -0.026124324914469213), + Complex64::new(-4.3021142204224816e-16, 0.06601980439593577), + Complex64::new(-0.9826870609532827, 2.7755575615628914e-16), + ], + [ + Complex64::new(-0.006212290419590961, -0.010739262071974568), + Complex64::new(-0.3589338503302527, 0.2076307761864266), + Complex64::new(0.9070757873156866, -5.412337245047638e-16), + Complex64::new(-6.245004513516506e-16, -0.07152302867497204), + ], + [ + Complex64::new(-0.9706933646378622, 2.7755575615628914e-17), + Complex64::new(2.6020852139652106e-18, -0.15594957493615416), + Complex64::new(0.03569705171577718, -0.061709927849413246), + Complex64::new(0.1457506851638859, 0.08431171332109447), + ], + [ + Complex64::new(7.112366251504909e-17, -0.16894909068671718), + Complex64::new(-0.8960049266516804, -3.608224830031759e-16), + Complex64::new(-0.35455306241796475, -0.20509664240745978), + Complex64::new(-0.014674445936026376, 0.02536789332498595), + ], + ] +} + pub(super) fn build_device_synthesis_context( device: &Device, circuit: &Circuit, diff --git a/crates/cqlib-core/src/compile/transform/canonicalize/canonicalize_test.rs b/crates/cqlib-core/src/compile/transform/canonicalize/canonicalize_test.rs index 5488b9de..566e5fb1 100644 --- a/crates/cqlib-core/src/compile/transform/canonicalize/canonicalize_test.rs +++ b/crates/cqlib-core/src/compile/transform/canonicalize/canonicalize_test.rs @@ -11,11 +11,13 @@ // that they have been altered from the originals. use super::{CanonicalizeConfig, Canonicalizer, canonicalize_circuit}; +use crate::circuit::circuit_impl::Circuit; +use crate::circuit::circuit_to_matrix::circuit_to_matrix; use crate::circuit::gate::FrozenCircuit; use crate::circuit::{ - Circuit, CircuitError, CircuitGate, CircuitParam, ClassicalControlOp, ClassicalDataOp, - ClassicalExpr, ClassicalType, Directive, Instruction, MCGate, Parameter, ParameterValue, Qubit, - StandardGate, UnitaryGate, ValueInstruction, ValueOperation, circuit_to_matrix, + CircuitError, CircuitGate, CircuitParam, ClassicalControlOp, ClassicalDataOp, ClassicalExpr, + ClassicalType, Directive, Instruction, MCGate, Parameter, ParameterValue, Qubit, StandardGate, + UnitaryGate, ValueInstruction, ValueOperation, }; use crate::compile::test_utils::generated_small_matrix_circuit; use crate::compile::transform::{RewriteEdits, TransformOutcome, TransformerTestExt}; @@ -1043,19 +1045,43 @@ fn canonicalize_phase_fast_path_does_not_accept_negative_zero() { } #[test] -fn canonical_transform_normalizes_global_phase_accumulator_residue() { +fn canonical_transform_preserves_nonzero_global_phase_residue() { let mut circuit = Circuit::new(1); - circuit.set_global_phase(Parameter::from(-3.330_669_073_875_469_6e-16)); + let phase = Parameter::from(-3.330_669_073_875_469_6e-16); + circuit.set_global_phase(phase.clone()); circuit.h(Qubit::new(0)).unwrap(); let first = Canonicalizer::production().run(&circuit).unwrap(); - assert!(first.changed); - assert_eq!(first.circuit.global_phase(), Parameter::from(0.0)); + assert!(!first.changed); + assert_eq!(first.circuit.global_phase(), phase); let second = Canonicalizer::production().run(&first.circuit).unwrap(); assert!(!second.changed); } +#[test] +fn canonical_transform_preserves_small_nonzero_rotation_angles() { + let mut circuit = Circuit::new(1); + circuit.rz(Qubit::new(0), Parameter::from(3e-16)).unwrap(); + let result = Canonicalizer::production().run(&circuit).unwrap(); + assert_eq!(result.circuit.operations().len(), 1); + assert_eq!( + result + .circuit + .resolve_parameter(&result.circuit.operations()[0].params[0]) + .unwrap() + .evaluate(&None) + .unwrap(), + 3e-16 + ); + assert!( + !Canonicalizer::production() + .run(&result.circuit) + .unwrap() + .changed + ); +} + #[test] fn canonicalization_is_idempotent_for_mixed_production_input() { let mut circuit = Circuit::new(3); diff --git a/crates/cqlib-core/src/compile/transform/canonicalize/canonicalizer.rs b/crates/cqlib-core/src/compile/transform/canonicalize/canonicalizer.rs index df075031..5a0ee49c 100644 --- a/crates/cqlib-core/src/compile/transform/canonicalize/canonicalizer.rs +++ b/crates/cqlib-core/src/compile/transform/canonicalize/canonicalizer.rs @@ -267,15 +267,6 @@ impl<'a> CanonicalizeRound<'a> { fn run(mut self) -> Result<(Circuit, Vec>), CompilerError> { self.top_phase = self.canonicalize_parameter(self.top_phase.clone())?; - if !self.source.operations().is_empty() && !self.top_phase.is_canonical_positive_zero() { - // The previous operation loop normalized `current + 0` once for - // every source operation, including operations with no phase - // contribution. Preserve that representation for tiny numeric - // residues with one up-front normalization instead of repeating - // the same symbolic work for every operation. - self.top_phase = - self.canonicalize_parameter(self.top_phase.clone() + Parameter::from(0.0))?; - } let mut top_level = Vec::with_capacity(self.source.operations().len()); let mut provenance = Vec::with_capacity(self.source.operations().len()); diff --git a/crates/cqlib-core/src/compile/transform/canonicalize/verify.rs b/crates/cqlib-core/src/compile/transform/canonicalize/verify.rs index 337b3cf4..a15fdee9 100644 --- a/crates/cqlib-core/src/compile/transform/canonicalize/verify.rs +++ b/crates/cqlib-core/src/compile/transform/canonicalize/verify.rs @@ -72,23 +72,6 @@ pub fn verify_circuit(circuit: &Circuit, mode: VerifyMode<'_>) -> Result<(), Com verify_parameter_finite(&global_phase, "global phase")?; if matches!(mode, VerifyMode::Output { .. }) { verify_parameter_canonical(&global_phase, circuit.global_phase_param(), "global phase")?; - // A canonicalization round accumulates a zero phase contribution for - // every retained root operation. The expression engine can normalize - // a tiny numeric residue while constructing that sum even when the - // residue alone is already a canonical numeric parameter. Reject that - // representation here so the verified fast path is a true fixed point. - if !circuit.operations().is_empty() && !global_phase.is_canonical_positive_zero() { - let accumulated = (global_phase.clone() + Parameter::from(0.0)) - .canonicalized() - .map_err(|error| { - CompilerError::Circuit(crate::circuit::CircuitError::InvalidParameter(error)) - })?; - if accumulated != global_phase { - return Err(CompilerError::InvariantViolation( - "global phase is not in accumulator-normal form".to_string(), - )); - } - } } verify_operations(circuit, circuit.operations(), "root", mode)?; diff --git a/crates/cqlib-core/src/compile/transform/commutative_cancellation/sets.rs b/crates/cqlib-core/src/compile/transform/commutative_cancellation/sets.rs index ee090d27..f576d2cd 100644 --- a/crates/cqlib-core/src/compile/transform/commutative_cancellation/sets.rs +++ b/crates/cqlib-core/src/compile/transform/commutative_cancellation/sets.rs @@ -12,8 +12,7 @@ //! Commutation-set grouping and cancellation-key analysis. //! -//! The analysis mirrors qiskit's `CommutativeCancellation` structure: -//! every wire's operation sequence is greedily partitioned into contiguous +//! Each wire's operation sequence is greedily partitioned into contiguous //! sets of pairwise exactly-commuting operations, and self-inverse gates are //! bucketed by a key of `(gate, canonical qargs, per-wire set indices)`. //! Two operations share a key only when everything between them on each of @@ -23,6 +22,9 @@ //! //! Sets are tracked per wire independently; a two-qubit gate therefore //! records one set index per qubit and the key keeps both as a tuple. +//! +//! Implementation reference for per-wire grouping and cancellation keys: +//! Qiskit's `CommutativeCancellation`. use crate::circuit::{Instruction, Operation, Parameter, Qubit, StandardGate}; use crate::compile::commutation::{Commutation, CommutationChecker}; diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/factors.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/factors.rs new file mode 100644 index 00000000..f4c21dbe --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/factors.rs @@ -0,0 +1,485 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2025-2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Equations (5)–(11) of Krol & Al-Ars. All block indices split on the MSB. +//! Demultiplexing takes a unitary Schur basis of U0 U1†, so the same W +//! reconstructs both branches, including their relative and common phases. + +use super::synthesis::{Matrix, failed}; +use crate::compile::CompilerError; +use faer::{Mat, Side}; +use ndarray::{Array1, Array2, ArrayView2, Axis, s}; +use num_complex::Complex64 as C; + +pub(super) fn to_faer(m: ArrayView2<'_, C>) -> Mat { + Mat::from_fn(m.nrows(), m.ncols(), |i, j| m[[i, j]]) +} + +fn from_faer(m: faer::MatRef<'_, C>) -> Matrix { + Array2::from_shape_fn((m.nrows(), m.ncols()), |(i, j)| m[(i, j)]) +} + +pub(super) fn adjoint(m: &Matrix) -> Matrix { + m.t().mapv(|z| z.conj()) +} + +pub(super) fn residual(a: &Matrix, b: &Matrix) -> f64 { + a.iter() + .zip(b) + .map(|(a, b)| (a - b).norm()) + .fold(0.0, |max, x| { + if x.is_finite() { + x.max(max) + } else { + f64::INFINITY + } + }) +} + +pub(super) fn validate_input(matrix: &Matrix, atol: f64) -> Result { + let n = matrix.nrows(); + if !atol.is_finite() || atol < 0.0 { + return Err(CompilerError::InvalidInput( + "Block-ZXZ requires finite nonnegative atol".into(), + )); + } + if matrix.ncols() != n || n < 2 || !n.is_power_of_two() { + return Err(CompilerError::InvalidInput(format!( + "expected square power-of-two dimension ≥ 2, got {}×{}", + n, + matrix.ncols() + ))); + } + if !matrix.iter().all(|z| z.is_finite()) { + return Err(CompilerError::InvalidInput( + "Block-ZXZ matrix contains non-finite entries".into(), + )); + } + let error = residual(&adjoint(matrix).dot(matrix), &Matrix::eye(n)); + if error > atol { + return Err(CompilerError::InvalidInput(format!( + "unitarity residual {error:e} exceeds {atol:e}" + ))); + } + Ok(error) +} + +pub(super) fn is_block_diagonal(m: &Matrix, atol: f64) -> bool { + let k = m.nrows() / 2; + (0..k).all(|i| (0..k).all(|j| m[[i, k + j]].norm() <= atol && m[[k + i, j]].norm() <= atol)) +} + +/// Returns the closest unitary matrix in every unitarily invariant norm via polar SVD. +pub(super) fn nearest_unitary(x: &Matrix) -> Result { + let svd = to_faer(x.view()) + .svd() + .map_err(|e| failed(format!("unitary projection SVD (dim {}): {e:?}", x.nrows())))?; + Ok(from_faer((svd.U() * svd.V().adjoint()).as_ref())) +} + +/// Full SVD supplies an orthonormal completion even when X has a null space. +fn polar(x: ArrayView2<'_, C>) -> Result<(Matrix, Matrix), CompilerError> { + let svd = to_faer(x) + .svd() + .map_err(|e| failed(format!("polar SVD (dim {}): {e:?}", x.nrows())))?; + let u = svd.U(); + let positive = u * svd.S() * u.adjoint(); + Ok(( + from_faer(positive.as_ref()), + from_faer((u * svd.V().adjoint()).as_ref()), + )) +} + +pub(super) struct Blocks { + pub a1: Matrix, + pub a2: Matrix, + pub b: Matrix, + pub c: Matrix, +} + +pub(super) fn split(u: &Matrix) -> Result { + let k = u.nrows() / 2; + let x = u.slice(s![..k, ..k]); + let (sx, ux) = polar(x)?; + let (sy, uy) = polar(u.slice(s![..k, k..]))?; + let c = adjoint(&ux).dot(&uy) * -C::i(); + let a1 = (sx + sy * C::i()).dot(&ux); + let a2 = &u.slice(s![k.., ..k]) + &u.slice(s![k.., k..]).dot(&adjoint(&c)); + let b = adjoint(&a1).dot(&x) * C::new(2.0, 0.0) - Matrix::eye(k); + Ok(Blocks { a1, a2, b, c }) +} + +pub(super) struct Demux { + pub v: Matrix, + pub d: Array1, + pub w: Matrix, +} + +/// Target single-linkage threshold for Hermitian eigenvalue clustering. Keeping +/// distinct clusters separated by at least 1e-2 bounds cross-cluster +/// eigenvector mixing to O(eps / 1e-2) ≈ 2e-14 even for opposite-sine pairs. +/// For dense wide spectra whose gaps are all below 1e-2, the threshold adapts +/// to half of the largest spectral gap so clusters always split cleanly. +const SCHUR_CLUSTER_TOL: f64 = 1e-2; + +fn hermitian_part(m: &Matrix) -> Mat { + let n = m.nrows(); + Mat::from_fn(n, n, |i, j| (m[[i, j]] + m[[j, i]].conj()) * 0.5) +} + +fn skew_hermitian_imag_part(m: &Matrix) -> Mat { + let n = m.nrows(); + Mat::from_fn(n, n, |i, j| { + (m[[i, j]] - m[[j, i]].conj()) * C::new(0.0, -0.5) + }) +} + +fn max_eigen_gap(s: faer::diag::DiagRef<'_, C>) -> f64 { + let p = s.dim(); + let mut best = 0.0_f64; + for i in 1..p { + let gap = (s[i] - s[i - 1]).norm(); + if gap > best { + best = gap; + } + } + best +} + +fn is_already_diagonal(m: &Matrix) -> bool { + let tol = 4.0 * f64::EPSILON; + m.indexed_iter() + .all(|((i, j), z)| i == j || z.norm() <= tol) +} + +/// Recursively computes an orthonormal Schur basis for a unitary (normal) block. +/// +/// If all eigenvalues of the block lie strictly inside an open arc of width +/// `2*pi/3` around their mean (verified via the exact eigenvalues of the aligned +/// Hermitian real part, not merely diagonal entries), then `sin(phi)` is +/// strictly monotonic with slope `> 0.5` and a single Hermitian eigendecomposition +/// of the aligned imaginary part diagonalizes the block to `O(p * eps)`. +/// +/// Otherwise the spectrum has spread `>= 0.5` along either the real or imaginary +/// axis, so picking the better-separated Hermitian axis and splitting at gaps +/// above `min(SCHUR_CLUSTER_TOL, 0.5 * max_gap)` strictly reduces every cluster +/// dimension until every subcluster is 1D or fits inside a narrow arc. +fn diagonalize_block(sub: &Matrix, rotation: C) -> Result { + let p = sub.nrows(); + if p <= 1 || is_already_diagonal(sub) { + return Ok(Matrix::eye(p)); + } + + let use_arc_alignment = rotation == C::new(1.0, 0.0); + let working = if use_arc_alignment { + let mu = (0..p).map(|i| sub[[i, i]]).sum::() / p as f64; + let mu_norm = mu.norm(); + if mu_norm > 0.5 { + sub * (mu.conj() / mu_norm) + } else { + sub.clone() + } + } else { + sub * rotation + }; + + let eig_re = hermitian_part(&working) + .self_adjoint_eigen(Side::Lower) + .map_err(|e| failed(format!("Schur real basis (dim {p}): {e:?}")))?; + + if use_arc_alignment && (0..p).all(|i| eig_re.S()[i].re > 0.5) { + let eig_tan = skew_hermitian_imag_part(&working) + .self_adjoint_eigen(Side::Lower) + .map_err(|e| failed(format!("Schur arc basis (dim {p}): {e:?}")))?; + return Ok(from_faer(eig_tan.U())); + } + + let max_gap_re = max_eigen_gap(eig_re.S()); + let (chosen, max_gap) = if max_gap_re >= SCHUR_CLUSTER_TOL { + (eig_re, max_gap_re) + } else { + let eig_im = skew_hermitian_imag_part(&working) + .self_adjoint_eigen(Side::Lower) + .map_err(|e| failed(format!("Schur imag basis (dim {p}): {e:?}")))?; + let max_gap_im = max_eigen_gap(eig_im.S()); + if max_gap_im > max_gap_re { + (eig_im, max_gap_im) + } else { + (eig_re, max_gap_re) + } + }; + + let mut v = from_faer(chosen.U()); + if max_gap <= f64::EPSILON { + return Ok(v); + } + + let tol = SCHUR_CLUSTER_TOL.min(0.5 * max_gap); + let s_vals = chosen.S(); + let mut s0 = 0; + while s0 < p { + let mut s1 = s0 + 1; + while s1 < p && (s_vals[s1] - s_vals[s1 - 1]).norm() <= tol { + s1 += 1; + } + if s1 - s0 > 1 && s1 - s0 < p { + let basis = v.slice(s![.., s0..s1]); + let child_sub = basis.t().mapv(|z| z.conj()).dot(sub).dot(&basis); + let child_u = diagonalize_block(&child_sub, C::new(1.0, 0.0))?; + let rotated = basis.dot(&child_u); + v.slice_mut(s![.., s0..s1]).assign(&rotated); + } + s0 = s1; + } + Ok(v) +} + +/// A unitary is normal. Its Hermitian real and imaginary parts commute, so +/// their joint orthonormal eigenbasis gives a diagonal complex Schur form. +fn schur_basis(m: &Matrix, rotation: C) -> Result { + diagonalize_block(m, rotation) +} + +pub(super) fn demux(u0: &Matrix, u1: &Matrix, atol: f64) -> Result { + let m = u0.dot(&adjoint(u1)); + // When the relative unitary is diagonal, the computational basis is + // already a Schur basis. Diagonalizing a nearly scalar matrix instead + // introduces arbitrary dense eigenvectors into otherwise simple leaves. + let roundoff = atol.min(8.0 * f64::EPSILON); + if m.indexed_iter() + .all(|((i, j), z)| i == j || z.norm() <= roundoff) + { + let d = m.diag().mapv(|z| C::from_polar(1., 0.5 * z.arg())); + let rows = d.view().insert_axis(Axis(1)); + let w = u1 * &rows; + if residual(&(&w * &rows), u0) <= roundoff + && residual(&(&w * &rows.mapv(|z| z.conj())), u1) <= roundoff + { + return Ok(Demux { + v: Matrix::eye(m.nrows()), + d, + w, + }); + } + } + let mut error = f64::INFINITY; + // Backup rotations separate spectra that remain poorly conditioned at 0. + for angle in [0.0, std::f64::consts::FRAC_PI_4, 1.0] { + let v = schur_basis(&m, C::from_polar(1.0, angle))?; + let vh = adjoint(&v); + // Only the diagonal of V† M V enters the square root. The row/column + // inner products avoid a second dense matrix multiplication. + let left = vh.dot(&m); + let d = Array1::from_shape_fn(m.nrows(), |i| { + let eigenvalue = left.row(i).dot(&v.column(i)); + C::from_polar(1.0, 0.5 * eigenvalue.arg()) + }); + let w = (&vh * &d.view().insert_axis(Axis(1))).dot(u1); + // D is stored as a vector. Broadcasting scales columns of V. + error = residual(&(&v * &d).dot(&w), u0) + .max(residual(&(&v * &d.mapv(|z| z.conj())).dot(&w), u1)); + if error <= atol { + return Ok(Demux { v, d, w }); + } + } + Err(failed(format!( + "demultiplexing (dim {}): maximum residual {error:e} exceeds {atol:e}", + u0.nrows() + ))) +} + +#[cfg(test)] +mod tests { + use super::super::synthesis::synthesis_test::{assert_matrix_close, seeded_unitary}; + use super::*; + + #[test] + fn polar_factors_complete_the_null_space_at_each_rank() { + let left = seeded_unitary(4, 81); + let right = seeded_unitary(4, 82); + for rank in 0..=4 { + let values = Array1::from_shape_fn(4, |i| { + C::from(if i < rank { 1. / (i + 1) as f64 } else { 0. }) + }); + let x = (&left * &values).dot(&right); + let (positive, unitary) = polar(x.view()).unwrap(); + assert_matrix_close(&positive, &(&left * &values).dot(&adjoint(&left)), 1e-13); + assert_matrix_close(&unitary.dot(&adjoint(&unitary)), &Matrix::eye(4), 1e-13); + assert_matrix_close(&positive.dot(&unitary), &x, 1e-13); + } + } + + #[test] + fn both_multiplexer_branches_reconstruct_with_degenerate_or_conjugate_spectra() { + let v = seeded_unitary(4, 21); + let u1 = seeded_unitary(4, 22); + for phases in [[0.9; 4], [0.7, -0.7, 1.3, -1.3], [0., 3e-9, 9e-9, 1.7]] { + let eigenvalues = Array1::from_vec(phases.to_vec()).mapv(|p| C::from_polar(1., p)); + let u0 = (&v * &eigenvalues).dot(&adjoint(&v)).dot(&u1); + let result = demux(&u0, &u1, 1e-12).unwrap(); + assert_matrix_close(&(&result.v * &result.d).dot(&result.w), &u0, 1e-12); + assert_matrix_close( + &(&result.v * &result.d.mapv(|z| z.conj())).dot(&result.w), + &u1, + 1e-12, + ); + assert_matrix_close(&adjoint(&result.v).dot(&result.v), &Matrix::eye(4), 1e-13); + } + } + + #[test] + fn failed_demultiplexing_reports_the_dimension_and_residual() { + let id = Matrix::eye(4); + let err = demux(&(&id * 2.), &id, 1e-12).err().unwrap().to_string(); + assert!( + err.contains("demultiplexing (dim 4)") && err.contains("residual"), + "{err}" + ); + } + + #[test] + fn finite_elements_that_overflow_the_gram_matrix_are_rejected() { + let matrix = Matrix::eye(4) * C::new(f64::MAX, 0.); + let err = validate_input(&matrix, f64::MAX).unwrap_err(); + assert!(matches!(err, CompilerError::InvalidInput(_))); + } + + #[test] + fn demux_resolves_dual_projection_near_conjugate_spectra() { + let v = seeded_unitary(4, 91); + let u1 = seeded_unitary(4, 92); + let half_pi = std::f64::consts::FRAC_PI_2; + let quarter_pi = std::f64::consts::FRAC_PI_4; + for gap in [ + 1e-12, 1e-9, 1.5e-8, 2e-8, 5e-8, 1e-7, 1e-6, 1e-4, 5e-3, 1.5e-2, + ] { + let phases = [half_pi, -half_pi + gap, quarter_pi, -3.0 * quarter_pi + gap]; + let eigenvalues = Array1::from_vec(phases.to_vec()).mapv(|p| C::from_polar(1., p)); + let u0 = (&v * &eigenvalues).dot(&adjoint(&v)).dot(&u1); + let result = demux(&u0, &u1, 1e-12).unwrap(); + assert_matrix_close(&(&result.v * &result.d).dot(&result.w), &u0, 1e-12); + assert_matrix_close( + &(&result.v * &result.d.mapv(|z| z.conj())).dot(&result.w), + &u1, + 1e-12, + ); + } + } + + #[test] + fn demux_resolves_single_linkage_chains_and_narrow_arcs() { + let v = seeded_unitary(8, 93); + let u1 = seeded_unitary(8, 94); + let half_pi = std::f64::consts::FRAC_PI_2; + let quarter_pi = std::f64::consts::FRAC_PI_4; + let pi = std::f64::consts::PI; + let spectra: Vec<[f64; 8]> = vec![ + // 3-way chains near both 0 and pi/4 projections + [ + half_pi - 1e-8, + -half_pi, + half_pi + 1e-8, + 0.1, + quarter_pi - 1e-8, + -3.0 * quarter_pi, + quarter_pi + 1e-8, + -0.3, + ], + // Narrow arc near pi/2 (where sin is stationary) + [ + half_pi - 3e-4, + half_pi - 2e-4, + half_pi - 1e-4, + half_pi, + half_pi + 1e-4, + half_pi + 2e-4, + -half_pi, + -half_pi + 1e-5, + ], + // Opposite-pole clusters around 0 and pi + [0.0, 1e-8, -1e-8, 2e-4, pi, pi - 1e-8, -pi + 1e-8, pi - 2e-4], + ]; + for phases in spectra { + let eigenvalues = Array1::from_vec(phases.to_vec()).mapv(|p| C::from_polar(1., p)); + let u0 = (&v * &eigenvalues).dot(&adjoint(&v)).dot(&u1); + let result = demux(&u0, &u1, 1e-12).unwrap(); + assert_matrix_close(&(&result.v * &result.d).dot(&result.w), &u0, 1e-12); + assert_matrix_close( + &(&result.v * &result.d.mapv(|z| z.conj())).dot(&result.w), + &u1, + 1e-12, + ); + assert_matrix_close(&adjoint(&result.v).dot(&result.v), &Matrix::eye(8), 1e-13); + } + } + + #[test] + fn nearest_unitary_projects_noisy_matrices_within_tolerance() { + let exact = seeded_unitary(8, 95); + let noisy = &exact * C::from(1.0 + 2e-7); + let projected = nearest_unitary(&noisy).unwrap(); + assert_matrix_close(&adjoint(&projected).dot(&projected), &Matrix::eye(8), 1e-14); + assert_matrix_close(&projected, &exact, 1e-14); + assert_matrix_close(&projected, &noisy, 1e-6); + } + + #[test] + fn demux_resolves_dense_wide_arc_and_full_circle_spectra() { + let dim = 256; + let v = seeded_unitary(dim, 96); + let vh = adjoint(&v); + let eye = Matrix::eye(dim); + let pi = std::f64::consts::PI; + + let wide_arc: Vec = (0..dim) + .map(|i| -1.2 + 2.4 * (i as f64) / ((dim - 1) as f64)) + .collect(); + let full_circle: Vec = (0..dim) + .map(|i| -pi + 2.0 * pi * (i as f64) / (dim as f64) + 0.37) + .collect(); + + for phases in [wide_arc, full_circle] { + let eigenvalues = Array1::from_vec(phases).mapv(|p| C::from_polar(1.0, p)); + let u0 = (&v * &eigenvalues).dot(&vh); + let result = demux(&u0, &eye, 1e-10).unwrap(); + assert_matrix_close(&(&result.v * &result.d).dot(&result.w), &u0, 1e-10); + assert_matrix_close( + &(&result.v * &result.d.mapv(|z| z.conj())).dot(&result.w), + &eye, + 1e-10, + ); + assert_matrix_close(&adjoint(&result.v).dot(&result.v), &eye, 1e-12); + } + } + + #[test] + fn demux_resolves_convex_diagonal_arc_trap() { + let dim = 16; + let v = seeded_unitary(dim, 97); + let u1 = seeded_unitary(dim, 98); + let mut phases = vec![0.0; dim]; + for (i, phase) in phases.iter_mut().enumerate().take(dim - 1) { + *phase = (i as f64) * 1e-7; + } + phases[dim - 1] = std::f64::consts::PI; + let eigenvalues = Array1::from_vec(phases).mapv(|p| C::from_polar(1.0, p)); + let u0 = (&v * &eigenvalues).dot(&adjoint(&v)).dot(&u1); + let result = demux(&u0, &u1, 1e-12).unwrap(); + assert_matrix_close(&(&result.v * &result.d).dot(&result.w), &u0, 1e-12); + assert_matrix_close( + &(&result.v * &result.d.mapv(|z| z.conj())).dot(&result.w), + &u1, + 1e-12, + ); + assert_matrix_close(&adjoint(&result.v).dot(&result.v), &Matrix::eye(dim), 1e-13); + } +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/leaf.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/leaf.rs new file mode 100644 index 00000000..b9a329f5 --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/leaf.rs @@ -0,0 +1,360 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2025-2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! A.2 carries a diagonal on the two lowest bits across each higher-bit +//! rotation, Hadamard, or controlled X. None of those gates changes either +//! low bit. The last leaf consumes the diagonal without producing another. + +use super::factors::{residual, to_faer}; +use super::synthesis::{BlockZxzDecomposeOptions, Matrix, Synthesis, failed}; +use crate::circuit::{Circuit, Parameter, Qubit, StandardGate}; +use crate::compile::CompilerError; +use crate::compile::transform::decompose::unitary::{ + TWO_QUBIT_EXACT_TOLERANCE, TwoQubitUnitaryDecomposeBasis, synthesize_numeric_2q_unitary, +}; +use ndarray::{Array1, array}; +use num_complex::Complex64 as C; + +type Diagonal = Array1; +type Leaf = (Circuit, Option); + +fn kak_circuit(u: &Matrix, atol: f64) -> Result { + // The first KAK argument represents the MSB of the 4×4 matrix. + let result = synthesize_numeric_2q_unitary( + u, + [Qubit::new(1), Qubit::new(0)], + TwoQubitUnitaryDecomposeBasis::Cx, + )?; + let mut c = Circuit::from_operations( + vec![Qubit::new(0), Qubit::new(1)], + result.operations, + None, + None, + )?; + c.set_global_phase(Parameter::from(result.global_phase)); + // KAK already checked its 4×4 candidate at its own tolerance. A caller + // requesting higher precision can reject a weak interaction rounded away. + if atol < TWO_QUBIT_EXACT_TOLERANCE { + let error = residual(&c.to_matrix(None)?, u); + if error > atol { + return Err(failed(format!( + "KAK leaf residual {error:e} exceeds {atol:e}" + ))); + } + } + Ok(c) +} + +/// Shende–Markov–Bullock, Proposition III.3. For S = Y ⊗ Y and M = U S Uᵀ, +/// `U` already lies in the <= 2-CX class iff `Im(tr(γ(U_SU4))) == 0`, where +/// `tr(γ(U_SU4)) = 2 (M[1,2] - M[0,3]) exp(-i arg(det U) / 2)`. Returns `None` +/// in that case so simple leaves are not perturbed by an unnecessary diagonal; +/// otherwise selects two row phases so the SU(4)-normalized spin-flip trace is real. +/// This is an ordinary transpose, not an adjoint. S has signed antidiagonal +/// (-1,1,1,-1), and only entries (1,2) and (0,3) of M enter the equation. +fn reducing_diagonal(u: &Matrix) -> Option { + let entry = |i: usize, j: usize| { + -u[[i, 0]] * u[[j, 3]] + u[[i, 1]] * u[[j, 2]] + u[[i, 2]] * u[[j, 1]] + - u[[i, 3]] * u[[j, 0]] + }; + let a = entry(1, 2); + let b = entry(0, 3); + let det_arg = to_faer(u.view()).determinant().arg(); + let trace_su4 = (a - b) * C::from_polar(2.0, -0.5 * det_arg); + if trace_su4.im.abs() <= 1e-13 { + return None; + } + let angle = a.arg() + b.arg() - det_arg; + let root = (b.norm() * angle.sin()).atan2(a.norm() + b.norm() * angle.cos()); + Some(array![ + C::ONE, + C::ONE, + C::from_polar(1.0, root - a.arg()), + C::from_polar(1.0, angle - root - b.arg()) + ]) +} + +fn synthesize(u: &Matrix, reduce: bool, atol: f64) -> Result { + if reduce && let Some(d) = reducing_diagonal(u) { + let target = u * &d.view().insert_axis(ndarray::Axis(1)); + if let Ok(c) = kak_circuit(&target, atol) + && c.operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count() + <= 2 + { + // C already owns its KAK phase: C = D U, hence D† C = U. + return Ok((c, Some(d.mapv(|z| z.conj())))); + } + } + Ok((kak_circuit(u, atol)?, None)) +} + +fn append_diagonal(output: &mut Circuit, d: &Diagonal) -> Result<(), CompilerError> { + let phase = d.mapv(|z| z.arg()); + let alpha = phase[2] - phase[0]; + let beta = phase[1] - phase[0]; + let gamma = phase[3] - phase[2] - phase[1] + phase[0]; + let parity = -gamma / 2.0; + let low = beta + gamma / 2.0; + let high = alpha + gamma / 2.0; + let (q0, q1) = (Qubit::new(0), Qubit::new(1)); + output.cx(q1, q0)?; + output.rz(q0, parity)?; + output.cx(q1, q0)?; + output.rz(q0, low)?; + output.rz(q1, high)?; + // On |00⟩ every RZ contributes exp(-i θ/2). Restore d00 exactly, + // including the P(θ) = exp(i θ/2) RZ(θ) conversion factors. + output.set_global_phase( + output.global_phase() + Parameter::from(phase[0] + (parity + low + high) / 2.0), + ); + Ok(()) +} + +pub(super) fn append( + output: &mut Circuit, + u: &Matrix, + pending: &mut Option, + reduce: bool, + atol: f64, +) -> Result<(), CompilerError> { + append_with(output, u, pending, atol, |target| { + synthesize(target, reduce, atol) + }) +} + +fn append_with( + output: &mut Circuit, + u: &Matrix, + pending: &mut Option, + atol: f64, + mut synth: impl FnMut(&Matrix) -> Result, +) -> Result<(), CompilerError> { + if let Some(d) = pending.as_ref() { + // The pending diagonal executes first; scale columns to form U D. + match synth(&(u * d)) { + Ok((c, next)) => { + output.compose(&c, None)?; + *pending = next; + return Ok(()); + } + Err(CompilerError::TransformFailed { .. }) => {} + Err(error) => return Err(error), + } + } + let (c, next) = match synth(u) { + Ok(leaf) => leaf, + Err(CompilerError::TransformFailed { .. }) => (euler_fallback(u, atol)?, None), + Err(error) => return Err(error), + }; + if let Some(d) = pending.as_ref() { + append_diagonal(output, d)?; + } + output.compose(&c, None)?; + *pending = next; + Ok(()) +} + +fn euler_fallback(u: &Matrix, atol: f64) -> Result { + // A nearly degenerate KAK can exhaust its CX templates. One more + // Block-ZXZ layer ends at Euler leaves and is cheap to verify at 4×4. + let options = BlockZxzDecomposeOptions { + opt_a1: false, + opt_a2: false, + opt_a2_force: false, + }; + let mut fallback = Synthesis::new(4, atol, options); + fallback.append_split(u, true)?; + let error = residual(&fallback.output.to_matrix(None)?, u); + if error > atol { + return Err(failed(format!( + "two-qubit Euler fallback: residual {error:e} exceeds {atol:e}" + ))); + } + Ok(fallback.output) +} + +#[cfg(test)] +mod tests { + use super::super::synthesis::synthesis_test::{assert_matrix_close, seeded_unitary}; + use super::*; + + #[test] + fn a2_remainder_includes_the_kak_phase_exactly_once() { + let target = seeded_unitary(4, 45) * C::from_polar(1.0, 0.37); + let (c, d) = synthesize(&target, true, 1e-10).unwrap(); + assert!(c.global_phase().evaluate(&None).unwrap().abs() > 1e-4); + let d = d.unwrap(); + assert!(d.iter().any(|z| (z - C::ONE).norm() > 1e-3)); + let actual = Matrix::from_diag(&d).dot(&c.to_matrix(None).unwrap()); + assert_matrix_close(&actual, &target, 1e-10); + // Negative control: the historical extra KAK phase breaks this fixture. + let duplicate = &actual * C::from_polar(1.0, c.global_phase().evaluate(&None).unwrap()); + let old = residual(&duplicate, &target); + assert!(old > 1e-3); + } + + #[test] + fn explicit_diagonal_preserves_constant_and_relative_phases() { + for phases in [Array1::from_elem(4, 0.37), array![-0.2, 0.53, 1.7, -2.98]] { + let d = phases.mapv(|p| C::from_polar(1.0, p)); + let mut c = Circuit::new(2); + append_diagonal(&mut c, &d).unwrap(); + assert_matrix_close(&c.to_matrix(None).unwrap(), &Matrix::from_diag(&d), 1e-14); + } + } + + #[test] + fn pending_diagonal_fallback_in_middle_and_last_leaf() { + for fail_at in [1, 2] { + let mut c = Circuit::new(2); + let mut pending = None; + let mut expected = Matrix::eye(4); + for i in 0..3 { + // A fixed Fourier transform with different row phases on each leaf. + // It does not commute with a non-scalar incoming diagonal. + let u = Matrix::from_shape_fn((4, 4), |(row, col)| { + let angle = std::f64::consts::FRAC_PI_2 * (row * col) as f64 + + 0.23 * ((i + 1) * row * row) as f64; + C::from_polar(0.5, angle) + }); + let mut attempts = 0; + append_with(&mut c, &u, &mut pending, 1e-10, |target| { + attempts += 1; + if i == fail_at && attempts == 1 { + return Err(failed("forced folded KAK failure".into())); + } + synthesize(target, i != 2, 1e-10) + }) + .unwrap(); + assert_eq!(attempts, if i == fail_at { 2 } else { 1 }); + expected = u.dot(&expected); + } + assert!(pending.is_none()); + assert_matrix_close(&c.to_matrix(None).unwrap(), &expected, 1e-10); + } + } + + #[test] + fn when_both_kak_attempts_fail_the_euler_fallback_composes_with_the_remainder() { + let diag = array![-0.3, 1.7, -2.1, 0.47].mapv(|a| C::from_polar(1., a)); + let mut pending = Some(diag.clone()); + let u = seeded_unitary(4, 89); + let mut output = Circuit::new(2); + let mut attempts = 0; + append_with(&mut output, &u, &mut pending, 1e-10, |target| { + attempts += 1; + let expected = if attempts == 1 { &u * &diag } else { u.clone() }; + assert_matrix_close(target, &expected, 1e-15); + Err(failed("forced KAK failure".into())) + }) + .unwrap(); + assert_eq!(attempts, 2); + assert!(pending.is_none()); + assert_matrix_close(&output.to_matrix(None).unwrap(), &(&u * &diag), 1e-12); + } + + #[test] + fn a_non_numeric_failure_preserves_the_pending_diagonal_and_output() { + let diag = array![C::i(), C::ONE, -C::i(), -C::ONE]; + let mut pending = Some(diag.clone()); + let mut output = Circuit::new(2); + let err = append_with(&mut output, &Matrix::eye(4), &mut pending, 1e-10, |_| { + Err(CompilerError::InvariantViolation("broken template".into())) + }) + .unwrap_err(); + assert!(matches!(err, CompilerError::InvariantViolation(_))); + assert_eq!(pending.unwrap(), diag); + assert!(output.operations().is_empty()); + } + + #[test] + fn smb_criterion_skips_leaves_already_within_two_cx() { + let phase = C::from_polar(1.0, 0.41); + // 0-CX product gate (I ⊗ I) + let id = Matrix::eye(4) * phase; + assert!(reducing_diagonal(&id).is_none()); + let (c_id, rem_id) = synthesize(&id, true, 1e-10).unwrap(); + assert!(rem_id.is_none()); + assert_eq!( + c_id.operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count(), + 0 + ); + + // 1-CX gate (CX) + let cx = ndarray::array![ + [C::ONE, C::ZERO, C::ZERO, C::ZERO], + [C::ZERO, C::ONE, C::ZERO, C::ZERO], + [C::ZERO, C::ZERO, C::ZERO, C::ONE], + [C::ZERO, C::ZERO, C::ONE, C::ZERO], + ] * phase; + assert!(reducing_diagonal(&cx).is_none()); + let (c_cx, rem_cx) = synthesize(&cx, true, 1e-10).unwrap(); + assert!(rem_cx.is_none()); + assert_eq!( + c_cx.operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count(), + 1 + ); + + // 2-CX gate (iSWAP) + let iswap = ndarray::array![ + [C::ONE, C::ZERO, C::ZERO, C::ZERO], + [C::ZERO, C::ZERO, C::i(), C::ZERO], + [C::ZERO, C::i(), C::ZERO, C::ZERO], + [C::ZERO, C::ZERO, C::ZERO, C::ONE], + ] * phase; + assert!(reducing_diagonal(&iswap).is_none()); + let (c_iswap, rem_iswap) = synthesize(&iswap, true, 1e-10).unwrap(); + assert!(rem_iswap.is_none()); + assert_eq!( + c_iswap + .operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count(), + 2 + ); + + // 3-CX gates (SWAP and generic random) still emit a reducing diagonal and 2 CX. + let swap = ndarray::array![ + [C::ONE, C::ZERO, C::ZERO, C::ZERO], + [C::ZERO, C::ZERO, C::ONE, C::ZERO], + [C::ZERO, C::ONE, C::ZERO, C::ZERO], + [C::ZERO, C::ZERO, C::ZERO, C::ONE], + ] * phase; + for target in [swap, seeded_unitary(4, 46) * phase] { + assert!(reducing_diagonal(&target).is_some()); + let (c, rem) = synthesize(&target, true, 1e-10).unwrap(); + let d = rem.unwrap(); + assert_eq!( + c.operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count(), + 2 + ); + assert_matrix_close( + &Matrix::from_diag(&d).dot(&c.to_matrix(None).unwrap()), + &target, + 1e-10, + ); + } + } +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/mod.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/mod.rs new file mode 100644 index 00000000..19906b75 --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/mod.rs @@ -0,0 +1,23 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2025-2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Recursive Block-ZXZ synthesis of numeric unitary matrices. +//! [Krol & Al-Ars, §§4–5](https://arxiv.org/html/2403.13692v2#S4). + +mod factors; +mod leaf; +mod synthesis; +mod ucrz; + +pub use synthesis::{ + BlockZxzDecomposeOptions, decompose_block_zxz, decompose_block_zxz_with_options, +}; diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/synthesis.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/synthesis.rs new file mode 100644 index 00000000..ba818bdd --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/synthesis.rs @@ -0,0 +1,225 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2025-2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Recursive synthesis of a numeric unitary, including its global phase. +//! [Krol & Al-Ars, §§4–5](https://arxiv.org/html/2403.13692v2#S4). +//! Each layer splits the highest matrix bit. Local circuit qubit zero is +//! the least significant bit. The four recursive blocks are emitted in +//! execution order, sharing the A.2 diagonal across recursive boundaries. + +use super::factors::{demux, is_block_diagonal, nearest_unitary, split, validate_input}; +use super::leaf; +use super::ucrz::{self, Chain}; +use crate::circuit::{Circuit, Parameter, Qubit}; +use crate::compile::CompilerError; +use crate::compile::transform::decompose::unitary::synthesize_numeric_1q_unitary; +use ndarray::{Array1, Array2, s}; +use num_complex::Complex64; + +pub(super) type Matrix = Array2; + +/// Controls the two independent CX reductions in Section 5. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct BlockZxzDecomposeOptions { + /// Absorb the two outer UCRZ boundary CX gates into the middle multiplexer. + pub opt_a1: bool, + /// Transfer a diagonal from each two-qubit leaf to its successor. + pub opt_a2: bool, + /// Allow diagonal transfer on block-diagonal inputs when A.2 is enabled. + pub opt_a2_force: bool, +} + +impl Default for BlockZxzDecomposeOptions { + fn default() -> Self { + Self { + opt_a1: true, + opt_a2: true, + opt_a2_force: false, + } + } +} + +pub(super) fn failed(reason: String) -> CompilerError { + CompilerError::TransformFailed { + name: "block_zxz", + reason, + } +} + +/// Synthesizes a finite square 2^n-dimensional unitary (n ≥ 1) in the +/// U/RZ/H/CX basis. The circuit includes the scalar synthesis phase. +/// Both CX optimizations default on, with automatic A.2 suppression for +/// block-diagonal inputs. See [`decompose_block_zxz_with_options`] for +/// absolute tolerance and error semantics. +pub fn decompose_block_zxz( + matrix: &Array2, + atol: f64, +) -> Result { + decompose_block_zxz_with_options(matrix, atol, &BlockZxzDecomposeOptions::default()) +} + +/// Synthesizes a matrix in computational basis order, with local q0 as +/// its least significant bit. The returned circuit reconstructs the full +/// input matrix, including global phase. Numerical fallback can add CX gates. +/// +/// `atol` is a finite, nonnegative absolute tolerance. It validates input +/// unitarity (`||M†M - I||_max <= atol`) and governs reconstruction checks on +/// demultiplexers and two-qubit leaves. Near-unitary inputs that pass input +/// validation are projected onto the nearest exact unitary `U_proj` (in every +/// unitarily invariant norm) when needed, and synthesis reconstructs `U_proj` +/// within `atol`. A KAK leaf without a validated CX template is split once +/// more into one-qubit gates and checked against the original 4×4 matrix. +/// +/// # Errors +/// Returns an input error for invalid tolerance, dimensions, non-finite +/// entries or failed unitarity. Numerical factorization or leaf synthesis +/// can fail when its residual exceeds the applicable tolerance. +pub fn decompose_block_zxz_with_options( + matrix: &Array2, + atol: f64, + options: &BlockZxzDecomposeOptions, +) -> Result { + let unitarity_error = validate_input(matrix, atol)?; + let mut options = *options; + options.opt_a2 &= options.opt_a2_force || !is_block_diagonal(matrix, atol); + // Project near-unitary inputs that exceed floating-point roundoff onto the + // nearest exact unitary before recursive splitting so coherent low-amplitude + // perturbations are not amplified across layers. If an unprojected input + // with nonzero unitarity error still fails numerically, retry on the polar + // projection. + let roundoff = 16.0 * (matrix.nrows() as f64).sqrt() * f64::EPSILON; + if unitarity_error > roundoff { + let projected = nearest_unitary(matrix)?; + let mut synthesis = Synthesis::new(projected.nrows(), atol, options); + synthesis.append(&projected, true)?; + return Ok(synthesis.output); + } + let mut synthesis = Synthesis::new(matrix.nrows(), atol, options); + match synthesis.append(matrix, true) { + Ok(()) => Ok(synthesis.output), + Err(CompilerError::TransformFailed { .. }) if unitarity_error > 0.0 => { + let projected = nearest_unitary(matrix)?; + let mut retry = Synthesis::new(projected.nrows(), atol, options); + retry.append(&projected, true)?; + Ok(retry.output) + } + Err(err) => Err(err), + } +} + +/// All recursive layers write to the same circuit. A pending diagonal belongs +/// to the two lowest qubits and survives intermediate gates on higher targets. +pub(super) struct Synthesis { + pub(super) output: Circuit, + pending: Option>, + atol: f64, + options: BlockZxzDecomposeOptions, +} + +impl Synthesis { + pub(super) fn new(dim: usize, atol: f64, options: BlockZxzDecomposeOptions) -> Self { + Self { + output: Circuit::new(dim.ilog2() as usize), + pending: None, + atol, + options, + } + } + + fn append(&mut self, u: &Matrix, last: bool) -> Result<(), CompilerError> { + match u.nrows() { + 2 => { + let gate = synthesize_numeric_1q_unitary(u)?; + self.output + .u(Qubit::new(0), gate.theta, gate.phi, gate.lambda)?; + self.output.set_global_phase( + self.output.global_phase() + Parameter::from(gate.global_phase), + ); + Ok(()) + } + 4 => leaf::append( + &mut self.output, + u, + &mut self.pending, + self.options.opt_a2 && !last, + self.atol, + ), + // A tolerance is appropriate for the optimization policy above, but + // skipping the off-diagonal blocks must preserve every nonzero entry. + _ if is_block_diagonal(u, 0.0) => self.append_block_diagonal(u, last), + _ => self.append_split(u, last), + } + } + + fn append_block_diagonal(&mut self, u: &Matrix, last: bool) -> Result<(), CompilerError> { + let k = u.nrows() / 2; + let upper = u.slice(s![..k, ..k]); + let lower = u.slice(s![k.., k..]); + if upper == lower { + // I ⊗ upper leaves the high qubit idle, including for a scalar phase. + return self.append(&upper.to_owned(), last); + } + let mux = demux(&upper.to_owned(), &lower.to_owned(), self.atol)?; + self.append(&mux.w, false)?; + ucrz::append(&mut self.output, &mux.d, Chain::Full)?; + self.append(&mux.v, last) + } + + pub(super) fn append_split(&mut self, u: &Matrix, last: bool) -> Result<(), CompilerError> { + let blocks = split(u)?; + let k = u.nrows() / 2; + let c = demux(&Matrix::eye(k), &blocks.c, self.atol)?; + let a = demux(&blocks.a1, &blocks.a2, self.atol)?; + let upper = a.w.dot(&c.v); + let mut lower = a.w.dot(&blocks.b).dot(&c.v); + if self.options.opt_a1 { + // Eq. (11): moving the closing CX through H turns it into CZ. + // In the lower branch conjugation by Z ⊗ I flips these two blocks. + for ((i, j), value) in lower.indexed_iter_mut() { + if (i < k / 2) != (j < k / 2) { + *value = -*value; + } + } + } + let b = demux(&upper, &lower, self.atol)?; + let top = Qubit::new(k.ilog2()); + self.append(&c.w, false)?; + ucrz::append( + &mut self.output, + &c.d, + if self.options.opt_a1 { + Chain::OpenTail + } else { + Chain::Full + }, + )?; + self.output.h(top)?; + self.append(&b.w, false)?; + ucrz::append(&mut self.output, &b.d, Chain::Full)?; + self.append(&b.v, false)?; + self.output.h(top)?; + ucrz::append( + &mut self.output, + &a.d, + if self.options.opt_a1 { + Chain::OpenHead + } else { + Chain::Full + }, + )?; + self.append(&a.v, last) + } +} + +#[cfg(test)] +#[path = "./synthesis_test.rs"] +pub(super) mod synthesis_test; diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/synthesis_test.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/synthesis_test.rs new file mode 100644 index 00000000..9d9964ea --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/synthesis_test.rs @@ -0,0 +1,1118 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2025-2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +use super::super::factors::{self, adjoint, residual}; +use super::*; +use crate::circuit::symbolic_matrix::SymbolicComplex; +use crate::circuit::{ + ClassicalControlOp, ClassicalExpr, Instruction, ParameterValue, StandardGate, UnitaryGate, + storage_operation_to_value, +}; +use crate::compile::transform::decompose::{ + decompose_unitaries, decompose_unitaries_with_rule_stats, +}; +use num_complex::Complex64 as C; +use rand::{Rng, SeedableRng, rngs::StdRng}; + +pub(crate) fn seeded_unitary(n: usize, seed: u64) -> Matrix { + let mut rng = StdRng::seed_from_u64(seed); + let source = Matrix::from_shape_simple_fn((n, n), || { + C::new(rng.random_range(-1.0..1.0), rng.random_range(-1.0..1.0)) + }); + let q = factors::to_faer(source.view()).qr().compute_Q(); + Matrix::from_shape_fn((n, n), |(i, j)| q[(i, j)]) +} + +pub(crate) fn assert_matrix_close(actual: &Matrix, expected: &Matrix, tol: f64) { + assert_eq!(actual.dim(), expected.dim()); + let error = residual(actual, expected); + assert!( + error <= tol, + "maximum matrix error {error:e}, allowed {tol:e}" + ); +} + +#[test] +fn unoptimized_then_a1_then_a2() { + for (n, counts) in [(8, [24, 22, 21, 19]), (16, [120, 110, 105, 95])] { + let u = seeded_unitary(n, 7); + for (index, (opt_a1, opt_a2)) in + [(false, false), (true, false), (false, true), (true, true)] + .into_iter() + .enumerate() + { + let options = BlockZxzDecomposeOptions { + opt_a1, + opt_a2, + opt_a2_force: false, + }; + let c = decompose_block_zxz_with_options(&u, 1e-10, &options).unwrap(); + assert_matrix_close(&c.to_matrix(None).unwrap(), &u, 1e-10); + let cx = c + .operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count(); + assert_eq!(cx, counts[index], "dim {n}, {options:?}"); + } + } +} + +#[test] +fn base_cases_structured_and_five_qubit_phase() { + let scalar = C::from_polar(1.0, 0.321); + let roll = Matrix::from_shape_fn( + (8, 8), + |(i, j)| if i == (j + 1) % 8 { C::ONE } else { C::ZERO }, + ); + let diagonal = Matrix::from_diag(&Array1::from_shape_fn(8, |i| { + C::from_polar(1.0, (i * i) as f64 * 0.17) + })); + for u in [ + seeded_unitary(2, 2) * scalar, + seeded_unitary(4, 3) * scalar, + Matrix::eye(8), + Matrix::eye(8) * scalar, + diagonal, + roll, + seeded_unitary(32, 13) * scalar, + ] { + assert_matrix_close( + &decompose_block_zxz(&u, 1e-10) + .unwrap() + .to_matrix(None) + .unwrap(), + &u, + 1e-10, + ); + } +} + +#[test] +fn block_diagonal_policy() { + let mut u = Matrix::zeros((8, 8)); + u.slice_mut(ndarray::s![..4, ..4]) + .assign(&seeded_unitary(4, 9)); + u.slice_mut(ndarray::s![4.., 4..]) + .assign(&seeded_unitary(4, 11)); + let run = |opt_a2, opt_a2_force| { + decompose_block_zxz_with_options( + &u, + 1e-10, + &BlockZxzDecomposeOptions { + opt_a1: true, + opt_a2, + opt_a2_force, + }, + ) + .unwrap() + }; + let normal = run(true, false); + assert_eq!(normal.operations(), run(false, false).operations()); + let forced = run(true, true); + assert_ne!(normal.operations(), forced.operations()); + for c in [normal, forced] { + assert_matrix_close(&c.to_matrix(None).unwrap(), &u, 1e-10); + } +} + +#[test] +fn schur_clusters_and_ucrz_branch_cut() { + let pi = std::f64::consts::PI; + let phases = ndarray::array![pi - 1e-9, -pi + 1e-9, 0.37, 0.37]; + let v = seeded_unitary(4, 8); + let u1 = seeded_unitary(4, 12); + let u0 = (&v * &phases.mapv(|p| C::from_polar(1.0, p))) + .dot(&adjoint(&v)) + .dot(&u1); + let factors::Demux { v, d, w } = demux(&u0, &u1, 1e-11).unwrap(); + // With 4×4 factors, 1e-11 resolves the 2e-9 phase separation + // while allowing rounding in the clustered eigenspace. + assert_matrix_close(&(&v * &d).dot(&w), &u0, 1e-11); + assert_matrix_close(&(&v * &d.mapv(|z| z.conj())).dot(&w), &u1, 1e-11); + let d = phases.mapv(|p| C::from_polar(1.0, p)); + let mut circuit = Circuit::new(3); + ucrz::append(&mut circuit, &d, Chain::Full).unwrap(); + let expected = Matrix::from_diag(&ndarray::concatenate![ + ndarray::Axis(0), + d, + d.mapv(|z| z.conj()) + ]); + assert_matrix_close(&circuit.to_matrix(None).unwrap(), &expected, 1e-13); +} + +#[test] +fn invalid_inputs() { + for bad in [ + Matrix::zeros((2, 3)), + Matrix::eye(1), + Matrix::eye(3), + Matrix::zeros((4, 4)), + Matrix::eye(2) * C::new(f64::INFINITY, 0.0), + Matrix::eye(2) * C::new(0.0, f64::NAN), + ] { + assert!(decompose_block_zxz(&bad, 1e-10).is_err()); + } + for atol in [-1.0, f64::NAN, f64::INFINITY] { + assert!(decompose_block_zxz(&Matrix::eye(2), atol).is_err()); + } +} + +#[test] +fn singular_quadrants_reconstruct_equation_five() { + // The cyclic permutation has a rank-three X and rank-one Y. + let u = Matrix::from_shape_fn((8, 8), |(i, j)| { + if i == (j + 1) % 8 { + C::from_polar(1.0, 0.23 * j as f64) + } else { + C::ZERO + } + }); + let b = split(&u).unwrap(); + let plus = (Matrix::eye(4) + &b.b) * C::new(0.5, 0.0); + let minus = Matrix::eye(4) - + + let mut rebuilt = Matrix::zeros((8, 8)); + rebuilt + .slice_mut(ndarray::s![..4, ..4]) + .assign(&b.a1.dot(&plus)); + rebuilt + .slice_mut(ndarray::s![..4, 4..]) + .assign(&b.a1.dot(&minus).dot(&b.c)); + rebuilt + .slice_mut(ndarray::s![4.., ..4]) + .assign(&b.a2.dot(&minus)); + rebuilt + .slice_mut(ndarray::s![4.., 4..]) + .assign(&b.a2.dot(&plus).dot(&b.c)); + assert_matrix_close(&rebuilt, &u, 1e-13); +} + +#[test] +fn block_zxz_cache_remaps_sparse_arguments_and_phase() { + let gate = UnitaryGate::new("asymmetric", 3, 0) + .with_matrix(seeded_unitary(8, 47)) + .unwrap(); + let mut circuit = Circuit::new(6); + for args in [[5, 1, 3], [2, 4, 0]] { + circuit + .unitary(gate.clone(), args.map(Qubit::new).to_vec()) + .unwrap(); + } + let (out, stats) = decompose_unitaries_with_rule_stats(&circuit, Default::default()).unwrap(); + assert_eq!((stats.hits, stats.misses), (1, 1)); + assert_matrix_close( + &out.into_circuit(&circuit).to_matrix(None).unwrap(), + &circuit.to_matrix(None).unwrap(), + 1e-10, + ); +} + +#[test] +fn block_zxz_phase_is_local_to_the_control_flow_body() { + let u = seeded_unitary(8, 37) * Complex64::from_polar(1., 0.73); + let gate = UnitaryGate::new("conditional", 3, 0) + .with_matrix(u.clone()) + .unwrap(); + let mut circuit = Circuit::new(3); + circuit + .if_else( + ClassicalExpr::bool_literal(true), + |body| { + body.append( + Instruction::UnitaryGate(Box::new(gate)), + [Qubit::new(2), Qubit::new(1), Qubit::new(0)], + Vec::::new(), + None, + ) + }, + |_| Ok(()), + ) + .unwrap(); + let out = decompose_unitaries(&circuit, Default::default()).unwrap(); + assert!(out.global_phase().is_zero()); + assert_matrix_close(&then_matrix(&out), &u, 1e-10); +} + +fn then_matrix(out: &Circuit) -> Matrix { + let Instruction::ClassicalControl(ClassicalControlOp::If(branch)) = + &out.operations()[0].instruction + else { + panic!("expected conditional") + }; + assert!(branch.else_body().unwrap().operations().is_empty()); + let operations = branch + .then_body() + .operations() + .iter() + .cloned() + .map(|op| storage_operation_to_value(op, &|p| out.parameter_value(p))) + .collect::, _>>() + .unwrap(); + let body = Circuit::from_operations(out.qubits().to_vec(), operations, None, None).unwrap(); + body.to_matrix(None).unwrap() +} + +#[test] +fn block_zxz_requires_resolved_matrix_parameters() { + let theta = Parameter::symbol("theta"); + let matrix = Array2::from_shape_fn((8, 8), |(i, j)| match (i, j) { + (7, 7) => SymbolicComplex::exp_i(theta.clone()), + _ if i == j => SymbolicComplex::one(), + _ => SymbolicComplex::zero(), + }); + let gate = UnitaryGate::new("conditional_phase", 3, 1) + .with_symbolic_matrix(["theta"], matrix) + .unwrap(); + let mut circuit = Circuit::new(3); + circuit + .unitary_with_params( + gate, + vec![Qubit::new(1), Qubit::new(0), Qubit::new(2)], + vec![Parameter::symbol("alpha").into()], + ) + .unwrap(); + let err = decompose_unitaries(&circuit, Default::default()).unwrap_err(); + assert!(err.to_string().contains("unresolved symbols: alpha")); +} + +#[test] +fn idle_high_bits_preserve_weak_xx_interactions() { + for dim in [8, 16] { + for angle in [1e-4_f64, 1e-6, 1e-9] { + let phase = C::from_polar(1., 0.31); + let u = Matrix::from_shape_fn((dim, dim), |(i, j)| match i ^ j { + 0 => phase * angle.cos(), + 3 => phase * C::i() * angle.sin(), + _ => C::ZERO, + }); + let circuit = decompose_block_zxz(&u, 1e-10).unwrap(); + assert_matrix_close(&circuit.to_matrix(None).unwrap(), &u, 1e-12); + assert!( + circuit + .operations() + .iter() + .flat_map(|op| &op.qubits) + .all(|q| q.index() < 2) + ); + } + } +} + +#[test] +fn structured_fourier_and_adjoint_on_nonstandard_array_layouts() { + for dim in [8, 16] { + let u = Matrix::from_shape_fn((dim, dim), |(i, j)| { + let angle = (std::f64::consts::TAU * (i * j) as f64 / dim as f64) + + 0.19 * (i * i) as f64 + - 0.31 * j as f64; + C::from_polar(1. / (dim as f64).sqrt(), angle) + }); + for m in [ + u.clone().reversed_axes(), + adjoint(&u), + u.slice_move(s![..;-1,..;-1]), + ] { + assert_matrix_close( + &decompose_block_zxz(&m, 1e-10) + .unwrap() + .to_matrix(None) + .unwrap(), + &m, + 1e-10, + ); + } + } +} + +#[test] +fn small_nonzero_off_diagonal_blocks_survive_the_a2_policy_threshold() { + let angle = 4e-9_f64; + let u = Matrix::from_shape_fn((8, 8), |(i, j)| match i ^ j { + 0 => C::from(angle.cos()), + 4 => C::i() * angle.sin(), + _ => C::ZERO, + }); + // The policy classifies this as block-diagonal at 1e-8. The structural + // shortcut must still retain the MSB rotation, visible at 1e-11. + assert_matrix_close( + &decompose_block_zxz(&u, 1e-8) + .unwrap() + .to_matrix(None) + .unwrap(), + &u, + 1e-11, + ); +} + +#[test] +fn force_alone_does_not_enable_diagonal_transfer() { + let options = BlockZxzDecomposeOptions { + opt_a2: false, + ..Default::default() + }; + let mut u = Matrix::eye(8); + u.slice_mut(s![4.., 4..]).assign(&seeded_unitary(4, 5)); + let normal = decompose_block_zxz_with_options(&u, 1e-10, &options).unwrap(); + let forced = decompose_block_zxz_with_options( + &u, + 1e-10, + &BlockZxzDecomposeOptions { + opt_a2_force: true, + ..options + }, + ) + .unwrap(); + assert_eq!(normal.operations(), forced.operations()); + assert_matrix_close(&forced.to_matrix(None).unwrap(), &u, 1e-10); +} + +#[test] +fn optimized_recursion_reconstructs_multiple_seeded_unitaries() { + for dim in [8, 16, 32] { + for seed in [17, 31, 65] { + let u = seeded_unitary(dim, seed) * C::from_polar(1., -(seed as f64)); + let c = decompose_block_zxz(&u, 1e-10).unwrap(); + assert!(c.operations().iter().all(|op| matches!( + op.instruction.standard_gate(), + Some(StandardGate::U | StandardGate::RZ | StandardGate::H | StandardGate::CX) + ))); + assert_matrix_close(&c.to_matrix(None).unwrap(), &u, 1e-10); + } + } +} + +#[test] +fn a_slightly_perturbed_controlled_x_can_use_euler_leaves() { + // CX · F diag(exp(i ε [0,1,3,7])) F†. The nearly coincident + // eigenphases can leave the KAK planner without a validated CX template. + let f = ndarray::array![ + [C::ONE, C::ONE, C::ONE, C::ONE], + [C::ONE, -C::i(), -C::ONE, C::i()], + [C::ONE, -C::ONE, C::ONE, -C::ONE], + [C::ONE, C::i(), -C::ONE, -C::i()] + ] * 0.5; + for gap in [1e-7, 1e-8, 1e-9] { + let phases = ndarray::array![0., 1., 3., 7.].mapv(|k| C::from_polar(1., k * gap)); + let u = (&f * &phases) + .dot(&adjoint(&f)) + .select(ndarray::Axis(0), &[0, 1, 3, 2]); + assert_matrix_close( + &decompose_block_zxz(&u, 1e-10) + .unwrap() + .to_matrix(None) + .unwrap(), + &u, + 1e-10, + ); + } +} + +#[test] +fn tight_leaf_tolerance_preserves_small_but_resolvable_interactions() { + let angle = 1e-11_f64; + let u = Matrix::from_shape_fn((4, 4), |(i, j)| match i ^ j { + 0 => C::from(angle.cos()), + 3 => C::i() * angle.sin(), + _ => C::ZERO, + }); + assert_matrix_close( + &decompose_block_zxz(&u, 1e-13) + .unwrap() + .to_matrix(None) + .unwrap(), + &u, + 1e-13, + ); +} + +#[test] +fn pass_keeps_a_sub_picoradian_phase_at_root_and_in_a_conditional() { + let phase = 4e-13; + let u = Matrix::eye(8) * C::from_polar(1., phase); + let gate = UnitaryGate::new("small_phase", 3, 0) + .with_matrix(u.clone()) + .unwrap(); + let q = [Qubit::new(0), Qubit::new(1), Qubit::new(2)]; + let mut source = Circuit::new(3); + source.unitary(gate.clone(), q.to_vec()).unwrap(); + let root = decompose_unitaries(&source, Default::default()).unwrap(); + assert_matrix_close(&root.to_matrix(None).unwrap(), &u, 1e-14); + let mut source = Circuit::new(3); + source + .if_else( + ClassicalExpr::bool_literal(true), + |body| { + body.append( + Instruction::UnitaryGate(Box::new(gate)), + q, + Vec::::new(), + None, + ) + }, + |_| Ok(()), + ) + .unwrap(); + let conditional = decompose_unitaries(&source, Default::default()).unwrap(); + assert!(conditional.global_phase().is_zero()); + assert_matrix_close(&then_matrix(&conditional), &u, 1e-14); +} + +#[test] +fn weak_interaction_with_a_relative_phase_on_the_high_bit() { + // diag(1,i) ⊗ I ⊗ exp(i ε XX), times a global phase. A dense basis + // change of the scalar relative unitary can amplify error in later leaves. + let angle = 1e-6_f64; + let u = Matrix::from_shape_fn((16, 16), |(i, j)| { + let phase = C::from_polar(1., 0.31) * if i >= 8 { C::i() } else { C::ONE }; + match i ^ j { + 0 => phase * angle.cos(), + 3 => phase * C::i() * angle.sin(), + _ => C::ZERO, + } + }); + assert_matrix_close( + &decompose_block_zxz(&u, 1e-10) + .unwrap() + .to_matrix(None) + .unwrap(), + &u, + 1e-12, + ); +} + +#[test] +fn dense_and_block_diagonal_adversarial_demux_spectra() { + let half_pi = std::f64::consts::FRAC_PI_2; + let quarter_pi = std::f64::consts::FRAC_PI_4; + let v4 = seeded_unitary(4, 101); + let u1_4 = seeded_unitary(4, 102); + let l1 = seeded_unitary(4, 103); + let l2 = seeded_unitary(4, 104); + + for gap in [1.5e-8, 2e-8, 5e-8, 1e-7, 1e-6] { + let phases = ndarray::array![half_pi, -half_pi + gap, quarter_pi, -3.0 * quarter_pi + gap]; + // Block-diagonal 3q matrix whose relative unitary has pairs near both 0 and pi/4. + let m = (&v4 * &phases.mapv(|p| C::from_polar(1., p))).dot(&adjoint(&v4)); + let mut bd = Matrix::zeros((8, 8)); + bd.slice_mut(s![..4, ..4]).assign(&m.dot(&u1_4)); + bd.slice_mut(s![4.., 4..]).assign(&u1_4); + assert_matrix_close( + &decompose_block_zxz(&bd, 1e-10) + .unwrap() + .to_matrix(None) + .unwrap(), + &bd, + 1e-10, + ); + + // Fully dense non-block-diagonal 3q matrix whose split() yields C = M†. + let c_mat = (&v4 * &phases.mapv(|p| C::from_polar(1., -p))).dot(&adjoint(&v4)); + let uy = &c_mat * C::i(); + let (sin_t, cos_t) = 0.63_f64.sin_cos(); + let mut dense = Matrix::zeros((8, 8)); + dense + .slice_mut(s![..4, ..4]) + .assign(&(&l1 * C::from(cos_t))); + dense + .slice_mut(s![..4, 4..]) + .assign(&(l1.dot(&uy) * C::from(sin_t))); + dense + .slice_mut(s![4.., ..4]) + .assign(&(&l2 * C::from(-sin_t))); + dense + .slice_mut(s![4.., 4..]) + .assign(&(l2.dot(&uy) * C::from(cos_t))); + assert_matrix_close( + &decompose_block_zxz(&dense, 1e-10) + .unwrap() + .to_matrix(None) + .unwrap(), + &dense, + 1e-10, + ); + // Also verify through the circuit-level pass. + let gate = UnitaryGate::new("adv_dense", 3, 0) + .with_matrix(dense.clone()) + .unwrap(); + let mut circuit = Circuit::new(3); + circuit + .unitary(gate, vec![Qubit::new(2), Qubit::new(1), Qubit::new(0)]) + .unwrap(); + let out = decompose_unitaries(&circuit, Default::default()).unwrap(); + assert_matrix_close(&out.to_matrix(None).unwrap(), &dense, 1e-10); + } + + // 4q block-diagonal matrix with 3-way chains near both 0 and pi/4. + let v8 = seeded_unitary(8, 105); + let u1_8 = seeded_unitary(8, 106); + for step in [1e-8, 1.4e-8, 2e-8] { + let phases = ndarray::array![ + half_pi - step, + -half_pi, + half_pi + step, + 0.1, + quarter_pi - step, + -3.0 * quarter_pi, + quarter_pi + step, + -0.3 + ]; + let m8 = (&v8 * &phases.mapv(|p| C::from_polar(1., p))).dot(&adjoint(&v8)); + let mut u16 = Matrix::zeros((16, 16)); + u16.slice_mut(s![..8, ..8]).assign(&m8.dot(&u1_8)); + u16.slice_mut(s![8.., 8..]).assign(&u1_8); + assert_matrix_close( + &decompose_block_zxz(&u16, 1e-10) + .unwrap() + .to_matrix(None) + .unwrap(), + &u16, + 1e-10, + ); + } +} + +#[test] +fn loose_tolerance_projects_slightly_non_unitary_inputs() { + for (dim, seed) in [(2, 111), (4, 112), (8, 113), (16, 114)] { + let exact = seeded_unitary(dim, seed) * C::from_polar(1., 0.42); + // Unitarity residual is ~4e-7, well below atol = 1e-5, but above 1q/2q UNITARY_EPS (1e-8). + let noisy = &exact * C::from(1.0 + 2e-7); + let circuit = decompose_block_zxz(&noisy, 1e-5).unwrap(); + assert_matrix_close(&circuit.to_matrix(None).unwrap(), &noisy, 1e-5); + assert_matrix_close(&circuit.to_matrix(None).unwrap(), &exact, 1e-10); + } +} + +#[test] +fn zero_and_negative_zero_tolerance_on_exact_unitaries() { + for dim in [2, 4, 8] { + let eye = Matrix::eye(dim); + for atol in [0.0, -0.0] { + let circuit = decompose_block_zxz(&eye, atol).unwrap(); + assert_matrix_close(&circuit.to_matrix(None).unwrap(), &eye, 0.0); + } + let perturbed = &eye * C::from(1.0 + 1e-12); + assert!(matches!( + decompose_block_zxz(&perturbed, 0.0), + Err(CompilerError::InvalidInput(_)) + )); + } +} + +#[test] +fn near_singular_quadrants_reconstruct_for_all_options() { + let l1 = seeded_unitary(4, 121); + let l2 = seeded_unitary(4, 122); + let r1 = seeded_unitary(4, 123); + let r2 = seeded_unitary(4, 124); + let half_pi = std::f64::consts::FRAC_PI_2; + let quarter_pi = std::f64::consts::FRAC_PI_4; + + for thetas in [ + [half_pi; 4], + [0.0, 0.0, half_pi, half_pi], + [0.3, half_pi, half_pi, half_pi], + [half_pi - 1e-16, half_pi, 0.4, 0.9], + [half_pi - 1e-12, half_pi - 2e-12, 0.0, 1e-12], + [half_pi - 1e-8, half_pi - 1e-8, 1e-8, 1e-8], + [ + quarter_pi, + quarter_pi + 1e-12, + quarter_pi - 1e-12, + quarter_pi + 1e-8, + ], + ] { + let cos_v = Array1::from_vec(thetas.iter().map(|t| C::from(t.cos())).collect()); + let sin_v = Array1::from_vec(thetas.iter().map(|t| C::from(t.sin())).collect()); + let mut u = Matrix::zeros((8, 8)); + u.slice_mut(s![..4, ..4]) + .assign(&(&l1 * &cos_v).dot(&adjoint(&r1))); + u.slice_mut(s![..4, 4..]) + .assign(&(-(&l1 * &sin_v).dot(&adjoint(&r2)))); + u.slice_mut(s![4.., ..4]) + .assign(&(&l2 * &sin_v).dot(&adjoint(&r1))); + u.slice_mut(s![4.., 4..]) + .assign(&(&l2 * &cos_v).dot(&adjoint(&r2))); + for options in [ + BlockZxzDecomposeOptions::default(), + BlockZxzDecomposeOptions { + opt_a1: false, + opt_a2: false, + opt_a2_force: false, + }, + BlockZxzDecomposeOptions { + opt_a1: true, + opt_a2: true, + opt_a2_force: true, + }, + ] { + let c = decompose_block_zxz_with_options(&u, 1e-10, &options).unwrap(); + assert_matrix_close(&c.to_matrix(None).unwrap(), &u, 1e-10); + } + } +} + +#[test] +fn structured_quantum_gates_preserve_matrix_and_global_phase() { + let phase = C::from_polar(1.0, -0.57); + let qft = |dim: usize| { + let scale = 1.0 / (dim as f64).sqrt(); + Matrix::from_shape_fn((dim, dim), |(i, j)| { + C::from_polar(scale, std::f64::consts::TAU * (i * j) as f64 / dim as f64) + }) + }; + let mut ccx = Matrix::eye(8); + ccx[[6, 6]] = C::ZERO; + ccx[[7, 7]] = C::ZERO; + ccx[[6, 7]] = C::ONE; + ccx[[7, 6]] = C::ONE; + + let mut cswap = Matrix::eye(8); + cswap[[5, 5]] = C::ZERO; + cswap[[6, 6]] = C::ZERO; + cswap[[5, 6]] = C::ONE; + cswap[[6, 5]] = C::ONE; + + let mut cccz = Matrix::eye(16); + cccz[[15, 15]] = -C::ONE; + + let grover8 = Matrix::from_elem((8, 8), C::from(0.25)) - Matrix::eye(8); + let mut anti_bd = Matrix::zeros((8, 8)); + anti_bd + .slice_mut(s![..4, 4..]) + .assign(&seeded_unitary(4, 131)); + anti_bd + .slice_mut(s![4.., ..4]) + .assign(&seeded_unitary(4, 132)); + + for u in [ + ccx * phase, + cswap * phase, + cccz * phase, + grover8 * phase, + qft(8) * phase, + qft(16) * phase, + anti_bd * phase, + -Matrix::eye(8), + ] { + let c = decompose_block_zxz(&u, 1e-10).unwrap(); + assert_matrix_close(&c.to_matrix(None).unwrap(), &u, 1e-10); + } +} + +#[test] +fn decompose_unitaries_resolved_symbolic_3q_matrix_and_parameter_cache() { + let theta = Parameter::symbol("theta"); + let matrix = Array2::from_shape_fn((8, 8), |(i, j)| match (i, j) { + (7, 7) => SymbolicComplex::exp_i(theta.clone()), + _ if i == j => SymbolicComplex::one(), + _ => SymbolicComplex::zero(), + }); + let gate = UnitaryGate::new("ccphase", 3, 1) + .with_symbolic_matrix(["theta"], matrix) + .unwrap(); + + // Resolved finite parameters synthesize accurately on permuted qubits, + // reuse the rule cache for identical values, and miss for distinct values. + let mut circuit = Circuit::new(3); + circuit + .unitary_with_params( + gate.clone(), + vec![Qubit::new(1), Qubit::new(0), Qubit::new(2)], + vec![ParameterValue::Fixed(0.43)], + ) + .unwrap(); + circuit + .unitary_with_params( + gate.clone(), + vec![Qubit::new(2), Qubit::new(1), Qubit::new(0)], + vec![ParameterValue::Fixed(0.43)], + ) + .unwrap(); + circuit + .unitary_with_params( + gate.clone(), + vec![Qubit::new(0), Qubit::new(2), Qubit::new(1)], + vec![ParameterValue::Fixed(-0.71)], + ) + .unwrap(); + let expected = circuit.to_matrix(None).unwrap(); + let (out, stats) = decompose_unitaries_with_rule_stats(&circuit, Default::default()).unwrap(); + assert_eq!((stats.hits, stats.misses, stats.inserts), (1, 2, 2)); + assert_matrix_close( + &out.into_circuit(&circuit).to_matrix(None).unwrap(), + &expected, + 1e-10, + ); + + // Non-finite fixed parameters are rejected at circuit construction. + let mut bad = Circuit::new(3); + assert!( + bad.unitary_with_params( + gate, + vec![Qubit::new(0), Qubit::new(1), Qubit::new(2)], + vec![ParameterValue::Fixed(f64::NAN)], + ) + .is_err() + ); +} + +#[test] +fn decompose_unitaries_overlapping_permuted_cache_and_mixed_arities() { + let g1 = UnitaryGate::new("u1", 1, 0) + .with_matrix(seeded_unitary(2, 141) * C::from_polar(1., 0.13)) + .unwrap(); + let g2 = UnitaryGate::new("u2", 2, 0) + .with_matrix(seeded_unitary(4, 142) * C::from_polar(1., -0.27)) + .unwrap(); + let g3 = UnitaryGate::new("u3", 3, 0) + .with_matrix(seeded_unitary(8, 143) * C::from_polar(1., 0.61)) + .unwrap(); + let g4 = UnitaryGate::new("u4", 4, 0) + .with_matrix(seeded_unitary(16, 144) * C::from_polar(1., -0.89)) + .unwrap(); + + let mut circuit = Circuit::new(5); + circuit.unitary(g1.clone(), vec![Qubit::new(0)]).unwrap(); + circuit.unitary(g1, vec![Qubit::new(4)]).unwrap(); + circuit + .unitary(g2.clone(), vec![Qubit::new(1), Qubit::new(2)]) + .unwrap(); + circuit + .unitary(g2, vec![Qubit::new(4), Qubit::new(0)]) + .unwrap(); + for args in [[0, 1, 2], [1, 2, 0], [2, 0, 1]] { + circuit + .unitary(g3.clone(), args.map(Qubit::new).to_vec()) + .unwrap(); + } + circuit + .unitary( + g4.clone(), + vec![Qubit::new(3), Qubit::new(0), Qubit::new(4), Qubit::new(1)], + ) + .unwrap(); + circuit + .unitary( + g4, + vec![Qubit::new(1), Qubit::new(4), Qubit::new(0), Qubit::new(3)], + ) + .unwrap(); + + let (out, stats) = decompose_unitaries_with_rule_stats(&circuit, Default::default()).unwrap(); + assert_eq!((stats.hits, stats.misses, stats.inserts), (5, 4, 4)); + assert_matrix_close( + &out.into_circuit(&circuit).to_matrix(None).unwrap(), + &circuit.to_matrix(None).unwrap(), + 1e-9, + ); +} + +#[test] +fn decompose_unitaries_control_flow_both_branches_and_recurse_false() { + use crate::compile::transform::decompose::UnitaryDecomposeConfig; + + let u_then = seeded_unitary(8, 151) * C::from_polar(1., 0.73); + let u_else = seeded_unitary(8, 152) * C::from_polar(1., -1.19); + let g_then = UnitaryGate::new("then3", 3, 0) + .with_matrix(u_then.clone()) + .unwrap(); + let g_else = UnitaryGate::new("else3", 3, 0) + .with_matrix(u_else.clone()) + .unwrap(); + + let mut circuit = Circuit::new(3); + circuit + .if_else( + ClassicalExpr::bool_literal(true), + |body| { + body.append( + Instruction::UnitaryGate(Box::new(g_then)), + [Qubit::new(2), Qubit::new(1), Qubit::new(0)], + Vec::::new(), + None, + ) + }, + |body| { + body.append( + Instruction::UnitaryGate(Box::new(g_else)), + [Qubit::new(2), Qubit::new(1), Qubit::new(0)], + Vec::::new(), + None, + ) + }, + ) + .unwrap(); + + // recurse_control_flow = false keeps the branch bodies untouched. + let no_recurse = decompose_unitaries( + &circuit, + UnitaryDecomposeConfig { + recurse_control_flow: false, + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(no_recurse, circuit); + + // recurse_control_flow = true lowers both branches with independent local GPhase. + let out = decompose_unitaries(&circuit, Default::default()).unwrap(); + assert!(out.global_phase().is_zero()); + let Instruction::ClassicalControl(ClassicalControlOp::If(branch)) = + &out.operations()[0].instruction + else { + panic!("expected conditional") + }; + let body_matrix = |ops: &[crate::circuit::Operation]| { + let vals = ops + .iter() + .cloned() + .map(|op| storage_operation_to_value(op, &|p| out.parameter_value(p))) + .collect::, _>>() + .unwrap(); + Circuit::from_operations(out.qubits().to_vec(), vals, None, None) + .unwrap() + .to_matrix(None) + .unwrap() + }; + assert_matrix_close( + &body_matrix(branch.then_body().operations()), + &u_then, + 1e-10, + ); + assert_matrix_close( + &body_matrix(branch.else_body().unwrap().operations()), + &u_else, + 1e-10, + ); +} + +#[test] +fn smb_criterion_avoids_inflating_structured_leaf_cx_count() { + let count_cx = |c: &Circuit| { + c.operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count() + }; + + // H ⊗ H ⊗ H has only simple leaves: A.2 must not add CX gates over opt_a2 = false. + let s = std::f64::consts::FRAC_1_SQRT_2; + let h3 = Matrix::from_shape_fn((8, 8), |(i, j)| { + let sign = if (i & j).count_ones() % 2 == 0 { + 1.0 + } else { + -1.0 + }; + C::from(sign * s * s * s) + }); + let h3_default = decompose_block_zxz(&h3, 1e-10).unwrap(); + let h3_no_a2 = decompose_block_zxz_with_options( + &h3, + 1e-10, + &BlockZxzDecomposeOptions { + opt_a1: true, + opt_a2: false, + opt_a2_force: false, + }, + ) + .unwrap(); + assert_matrix_close(&h3_default.to_matrix(None).unwrap(), &h3, 1e-10); + assert!( + count_cx(&h3_default) <= count_cx(&h3_no_a2), + "default CX ({}) exceeded opt_a2=false CX ({})", + count_cx(&h3_default), + count_cx(&h3_no_a2) + ); + + // Diagonal 3q/4q matrices with opt_a2_force=true stay at the same CX count as opt_a2=false. + for dim in [8, 16] { + let diag = Matrix::from_diag(&Array1::from_shape_fn(dim, |i| { + C::from_polar(1.0, 0.27 * (i * i + 1) as f64) + })); + let forced = decompose_block_zxz_with_options( + &diag, + 1e-10, + &BlockZxzDecomposeOptions { + opt_a1: true, + opt_a2: true, + opt_a2_force: true, + }, + ) + .unwrap(); + let plain = decompose_block_zxz_with_options( + &diag, + 1e-10, + &BlockZxzDecomposeOptions { + opt_a1: true, + opt_a2: false, + opt_a2_force: false, + }, + ) + .unwrap(); + assert_matrix_close(&forced.to_matrix(None).unwrap(), &diag, 1e-10); + assert_eq!(count_cx(&forced), count_cx(&plain)); + } +} + +#[test] +fn decompose_unitaries_respects_block_zxz_options() { + use crate::compile::transform::decompose::UnitaryDecomposeConfig; + + let count_cx = |c: &Circuit| { + c.operations() + .iter() + .filter(|op| op.instruction.standard_gate() == Some(StandardGate::CX)) + .count() + }; + + let u = seeded_unitary(8, 7) * C::from_polar(1., 0.29); + let gate = UnitaryGate::new("generic3", 3, 0).with_matrix(u).unwrap(); + let mut circuit = Circuit::new(3); + circuit + .unitary(gate, vec![Qubit::new(0), Qubit::new(1), Qubit::new(2)]) + .unwrap(); + let expected = circuit.to_matrix(None).unwrap(); + + let optimized = decompose_unitaries(&circuit, UnitaryDecomposeConfig::default()).unwrap(); + let unoptimized = decompose_unitaries( + &circuit, + UnitaryDecomposeConfig { + block_zxz_options: BlockZxzDecomposeOptions { + opt_a1: false, + opt_a2: false, + opt_a2_force: false, + }, + ..Default::default() + }, + ) + .unwrap(); + assert_eq!(count_cx(&optimized), 19); + assert_eq!(count_cx(&unoptimized), 24); + assert_matrix_close(&optimized.to_matrix(None).unwrap(), &expected, 1e-10); + assert_matrix_close(&unoptimized.to_matrix(None).unwrap(), &expected, 1e-10); +} + +#[test] +fn repeated_weak_xx_interaction_preserves_coherent_rotation() { + let weak_xx = |theta: f64| { + Matrix::from_shape_fn((8, 8), |(i, j)| match i ^ j { + 0 => C::from(theta.cos()), + 3 => C::i() * theta.sin(), + _ => C::ZERO, + }) + }; + for (angle, repeats) in [(9e-11_f64, 64usize), (8e-13_f64, 512usize)] { + let u = weak_xx(angle); + let gate = UnitaryGate::new("weak_xx_3q", 3, 0).with_matrix(u).unwrap(); + let mut circuit = Circuit::new(3); + for _ in 0..repeats { + circuit + .unitary( + gate.clone(), + vec![Qubit::new(2), Qubit::new(1), Qubit::new(0)], + ) + .unwrap(); + } + let expected = weak_xx(angle * repeats as f64); + let (out, stats) = + decompose_unitaries_with_rule_stats(&circuit, Default::default()).unwrap(); + assert_eq!((stats.hits, stats.misses), (repeats - 1, 1)); + assert_matrix_close( + &out.into_circuit(&circuit).to_matrix(None).unwrap(), + &expected, + 1e-10, + ); + } +} + +#[test] +fn near_tolerance_unitary_boundary_succeeds_in_block_zxz_and_pass() { + let base = seeded_unitary(8, 173); + let scaled = &base * C::from(1.0 + 4.5e-11); + let mut rng = StdRng::seed_from_u64(174); + let noise = Matrix::from_shape_simple_fn((8, 8), || { + C::new(rng.random_range(-1.0..1.0), rng.random_range(-1.0..1.0)) + }); + let probe = &base + &noise * C::from(1e-11); + let probe_err = residual(&adjoint(&probe).dot(&probe), &Matrix::eye(8)); + let anisotropic = &base + &noise * C::from(1e-11 * (9e-11 / probe_err)); + + for matrix in [scaled, anisotropic] { + let unitarity_err = residual(&adjoint(&matrix).dot(&matrix), &Matrix::eye(8)); + assert!(unitarity_err > 8e-11 && unitarity_err < 1e-10); + + let gate = UnitaryGate::new("near_tol_3q", 3, 0) + .with_matrix(matrix.clone()) + .unwrap(); + let direct = decompose_block_zxz(&matrix, 1e-10).unwrap(); + assert_matrix_close(&direct.to_matrix(None).unwrap(), &matrix, 1e-10); + + let mut circuit = Circuit::new(3); + circuit + .unitary(gate, vec![Qubit::new(2), Qubit::new(1), Qubit::new(0)]) + .unwrap(); + let out = decompose_unitaries(&circuit, Default::default()).unwrap(); + assert_matrix_close(&out.to_matrix(None).unwrap(), &matrix, 1e-10); + } +} + +#[test] +fn near_unitary_polar_projection_and_coherent_64x64_perturbation_succeed() { + // 1) 8x8 matrix passing input unitarity (<= 1e-10) whose Frobenius-optimal + // polar projection shifts a single entry by > 1e-10 in max-element norm. + let qft = Matrix::from_shape_fn((8, 8), |(i, j)| { + C::from_polar( + 1.0 / 8.0_f64.sqrt(), + std::f64::consts::TAU * (i * j) as f64 / 8.0, + ) + }); + let mut noisy = qft.clone(); + for j in 0..8 { + noisy[[0, j]] *= C::from(1.0 + 3.6e-10); + } + let unitarity_err = residual(&adjoint(&noisy).dot(&noisy), &Matrix::eye(8)); + let projected = factors::nearest_unitary(&noisy).unwrap(); + let proj_err = residual(&projected, &noisy); + assert!( + unitarity_err <= 1e-10 && proj_err > 1e-10, + "unitarity_err={unitarity_err:e}, proj_err={proj_err:e}" + ); + let direct = decompose_block_zxz(&noisy, 1e-10).unwrap(); + assert_matrix_close(&direct.to_matrix(None).unwrap(), &projected, 1e-10); + + let gate = UnitaryGate::new("polar_shift_3q", 3, 0) + .with_matrix(noisy.clone()) + .unwrap(); + let mut circuit = Circuit::new(3); + circuit + .unitary(gate, vec![Qubit::new(2), Qubit::new(1), Qubit::new(0)]) + .unwrap(); + let out = decompose_unitaries(&circuit, Default::default()).unwrap(); + assert_matrix_close(&out.to_matrix(None).unwrap(), &projected, 1e-10); + + // 2) 64x64 coherent rank-1 perturbation whose max-element Gram residual is + // ~8.55e-13 (below 64*n*eps) yet whose spectral error is 64x larger. + let n = 64usize; + let gram_noise = 0.94 * 64.0 * (n as f64) * f64::EPSILON; + let p = gram_noise / ((1.0 + (n as f64) * gram_noise).sqrt() + 1.0); + let coherent = Matrix::eye(n) + Matrix::from_elem((n, n), C::from(p)); + let coherent_gram = residual(&adjoint(&coherent).dot(&coherent), &Matrix::eye(n)); + assert!(coherent_gram < 1e-10); + let coherent_proj = factors::nearest_unitary(&coherent).unwrap(); + let coherent_out = decompose_block_zxz(&coherent, 1e-10).unwrap(); + assert_matrix_close( + &coherent_out.to_matrix(None).unwrap(), + &coherent_proj, + 1e-10, + ); +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/ucrz.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/ucrz.rs new file mode 100644 index 00000000..5cdfec95 --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/ucrz.rs @@ -0,0 +1,96 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2025-2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Uniformly controlled RZ on the MSB implements D ⊕ D†. Equation (4) +//! is a Walsh–Hadamard transform with Gray-permuted columns. + +use crate::circuit::{Circuit, CircuitError, Qubit}; +use ndarray::Array1; +use num_complex::Complex64; + +pub(super) enum Chain { + Full, + OpenTail, + OpenHead, +} + +pub(super) fn append( + output: &mut Circuit, + d: &Array1, + chain: Chain, +) -> Result<(), CircuitError> { + let mut angles: Vec<_> = d.iter().map(|z| -2.0 * z.arg()).collect(); + let n = angles.len(); + let mut stride = 1; + while stride < n { + for chunk in angles.chunks_exact_mut(2 * stride) { + let (left, right) = chunk.split_at_mut(stride); + for (a, b) in left.iter_mut().zip(right) { + (*a, *b) = (*a + *b, *a - *b); + } + } + stride *= 2; + } + let target = Qubit::new(n.ilog2()); + let gray = |i: usize| i ^ (i >> 1); + for step in 0..n { + // Reversal transposes the full chain. Its diagonal matrix is symmetric. + let reverse = matches!(chain, Chain::OpenHead); + let i = if reverse { n - 1 - step } else { step }; + let control = Qubit::new((gray(i) ^ gray((i + 1) % n)).trailing_zeros()); + if reverse && i + 1 < n { + output.cx(control, target)?; + } + output.rz(target, angles[gray(i)] / n as f64)?; + if !reverse && (i + 1 < n || matches!(chain, Chain::Full)) { + output.cx(control, target)?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::super::synthesis::{Matrix, synthesis_test::assert_matrix_close}; + use super::*; + + #[test] + fn restoring_either_open_boundary_reconstructs_every_control_word() { + // Close the missing CX on the appropriate side independently of the + // Gray-code generator. Each diagonal phase labels a distinct control word. + for controls in 1..=4 { + let size = 1 << controls; + let d = Array1::from_shape_fn(size, |i| { + Complex64::from_polar(1., 0.21 * (i * i + 1) as f64) + }); + let expected = Matrix::from_diag(&ndarray::concatenate![ + ndarray::Axis(0), + d, + d.mapv(|z| z.conj()) + ]); + for chain in [Chain::Full, Chain::OpenHead, Chain::OpenTail] { + let mut circuit = Circuit::new(controls + 1); + let top = Qubit::new(controls as u32); + let control = Qubit::new(controls as u32 - 1); + let open_tail = matches!(chain, Chain::OpenTail); + if matches!(chain, Chain::OpenHead) { + circuit.cx(control, top).unwrap(); + } + append(&mut circuit, &d, chain).unwrap(); + if open_tail { + circuit.cx(control, top).unwrap(); + } + assert_matrix_close(&circuit.to_matrix(None).unwrap(), &expected, 1e-13); + } + } + } +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/definition.rs b/crates/cqlib-core/src/compile/transform/decompose/definition.rs index 429e5f34..97fd9859 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/definition.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/definition.rs @@ -26,6 +26,7 @@ use crate::compile::transform::analysis::WorkflowCircuitAnalysis; use crate::compile::transform::rebuild::{CircuitRebuildContext, ClassicalRemap}; use crate::compile::transform::transformer::{PassApplicability, WorkflowPass}; use crate::compile::transform::{CircuitAnalysis, TransformOutcome, Transformer}; +use indexmap::IndexSet; use smallvec::{SmallVec, smallvec}; use std::collections::{HashMap, HashSet}; @@ -172,6 +173,8 @@ impl<'a> DefinitionExpander<'a> { self.expand_definition( gate.name(), definition.circuit(), + &definition.circuit().qubits(), + gate.signature_params(), gate.num_qubits(), gate.num_params(), operation, @@ -186,9 +189,13 @@ impl<'a> DefinitionExpander<'a> { Instruction::UnitaryGate(gate) => { if let Some(definition) = gate.circuit().as_ref() { self.changed = true; + // Circuit-backed unitaries use the cached live-symbol order, + // matching UnitaryGate::matrix_for_params. self.expand_definition( gate.label(), definition.circuit(), + &definition.qubits_in_numeric_order(), + definition.used_symbols(), gate.num_qubits() as usize, gate.num_params() as usize, operation, @@ -240,6 +247,8 @@ impl<'a> DefinitionExpander<'a> { &mut self, name: &str, definition: &Circuit, + definition_qubits: &[Qubit], + signature_params: &IndexSet, expected_qubits: usize, expected_params: usize, operation: &Operation, @@ -269,11 +278,10 @@ impl<'a> DefinitionExpander<'a> { ))); } - let definition_symbols = definition.symbols(); - if definition_symbols.len() != expected_params { + if signature_params.len() != expected_params { return Err(CompilerError::InvariantViolation(format!( - "definition '{name}' signature has {expected_params} parameters but backing circuit has {} symbols", - definition_symbols.len() + "definition '{name}' expects {expected_params} parameters but its signature has {} parameters", + signature_params.len() ))); } @@ -284,12 +292,13 @@ impl<'a> DefinitionExpander<'a> { // nested definition must receive a fresh binding table instead of a // merged parent table. Merging would make equal symbol names in nested // definitions accidentally capture outer bindings. - let mut next_symbol_bindings = HashMap::with_capacity(definition_symbols.len()); - for (symbol, value) in definition_symbols.iter().zip(resolved_params) { + // Only the call signature defines positional bindings. Live dependencies + // may omit unused formals, and the circuit registry may retain stale symbols. + let mut next_symbol_bindings = HashMap::with_capacity(signature_params.len()); + for (symbol, value) in signature_params.iter().zip(resolved_params) { next_symbol_bindings.insert(symbol.clone(), value); } - let definition_qubits = definition.qubits(); if definition_qubits.len() != expected_qubits { return Err(CompilerError::InvariantViolation(format!( "definition '{name}' signature has {expected_qubits} qubits but backing circuit has {} qubits", @@ -599,8 +608,9 @@ fn fresh_temp_symbol(index: usize, symbol: &str, occupied: &mut HashSet) #[cfg(test)] mod tests { use super::*; - use crate::circuit::ParameterValue; use crate::circuit::gate::{FrozenCircuit, UnitaryGate}; + use crate::circuit::test_utils::assert_matrix_approx_eq; + use crate::circuit::{CircuitGate, ParameterValue, circuit_to_matrix}; use crate::circuit::{ClassicalDataOp, ClassicalExpr}; use crate::compile::transform::TransformerTestExt; use ndarray::array; @@ -706,6 +716,192 @@ mod tests { assert_eq!(rz_param.evaluate(&Some(bindings)).unwrap(), 6.0); } + #[test] + fn expands_circuit_gate_using_declared_parameter_signature() { + let q0 = Qubit::new(0); + let mut expected = Circuit::new(1); + expected.rx(q0, -0.2).unwrap(); + expected.rz(q0, 0.7).unwrap(); + expected.set_global_phase(Parameter::from(-1.6)); + let expected_matrix = circuit_to_matrix(&expected, None).unwrap(); + + for stale_registry in [false, true] { + for unused_formal in [false, true] { + let mut definition = Circuit::new(1); + if stale_registry { + definition.add_parameter(Parameter::symbol("stale")); + } + definition.rx(q0, Parameter::symbol("theta")).unwrap(); + definition.rz(q0, Parameter::symbol("phi")).unwrap(); + definition + .set_global_phase(Parameter::symbol("theta") - Parameter::symbol("phi") * 2.0); + + let mut signature = vec!["phi".to_string(), "theta".to_string()]; + let mut args = vec![ParameterValue::from(0.7), ParameterValue::from(-0.2)]; + if unused_formal { + signature.insert(0, "unused".to_string()); + args.insert(0, ParameterValue::from(11.0)); + } + let gate = CircuitGate::with_signature( + "declared", + FrozenCircuit::new(definition), + signature, + ) + .unwrap(); + let mut circuit = Circuit::new(1); + circuit.circuit_gate(gate, vec![q0], args).unwrap(); + + let expanded = expand_definitions(&circuit).unwrap(); + assert_eq!(expanded.operations().len(), 2); + for actual in [&circuit, &circuit.decompose().unwrap(), &expanded] { + assert_matrix_approx_eq( + &circuit_to_matrix(actual, None).unwrap(), + &expected_matrix, + 1e-12, + ); + } + } + } + } + + #[test] + fn expands_inferred_signatures_without_removed_operation_symbols() { + let q0 = Qubit::new(0); + let mut definition = Circuit::new(1); + definition.rx(q0, Parameter::symbol("removed")).unwrap(); + definition.remove_operation(0).unwrap(); + definition.rx(q0, Parameter::symbol("theta")).unwrap(); + definition.rz(q0, Parameter::symbol("phi")).unwrap(); + let circuit_gate = definition.clone().to_gate("inferred").unwrap(); + let unitary_gate = UnitaryGate::new("inferred_unitary", 1, 2) + .with_circuit(Arc::new(FrozenCircuit::new(definition))) + .unwrap(); + + let mut expected = Circuit::new(1); + expected.rx(q0, 0.7).unwrap(); + expected.rz(q0, -0.2).unwrap(); + let expected_matrix = circuit_to_matrix(&expected, None).unwrap(); + for gate in [ + circuit_gate, + Instruction::UnitaryGate(Box::new(unitary_gate)), + ] { + let mut circuit = Circuit::new(1); + circuit + .append( + gate, + [q0], + [ParameterValue::from(0.7), ParameterValue::from(-0.2)], + None, + ) + .unwrap(); + let expanded = expand_definitions(&circuit).unwrap(); + for actual in [&circuit, &expanded] { + assert_matrix_approx_eq( + &circuit_to_matrix(actual, None).unwrap(), + &expected_matrix, + 1e-12, + ); + } + } + } + + #[test] + fn expands_phase_only_definition_with_unused_formal() { + let mut definition = Circuit::new(1); + definition.set_global_phase(Parameter::symbol("phase")); + let gate = CircuitGate::with_signature( + "phase_only", + FrozenCircuit::new(definition), + ["unused".to_string(), "phase".to_string()], + ) + .unwrap(); + let mut circuit = Circuit::new(1); + circuit + .append( + Instruction::CircuitGate(Box::new(gate)), + [Qubit::new(0)], + [ParameterValue::from(11.0), ParameterValue::from(0.7)], + None, + ) + .unwrap(); + let expanded = expand_definitions(&circuit).unwrap(); + assert!(expanded.operations().is_empty()); + assert!((expanded.global_phase().evaluate(&None).unwrap() - 0.7).abs() < 1e-12); + assert_matrix_approx_eq( + &circuit_to_matrix(&expanded, None).unwrap(), + &circuit_to_matrix(&circuit, None).unwrap(), + 1e-12, + ); + } + + #[test] + fn expands_nested_signatures_with_simultaneous_symbolic_arguments() { + let q0 = Qubit::new(0); + let theta = Parameter::symbol("theta"); + let phi = Parameter::symbol("phi"); + let mut leaf = Circuit::new(1); + leaf.rx(q0, theta.clone()).unwrap(); + leaf.rz(q0, phi.clone()).unwrap(); + leaf.set_global_phase(theta.clone() + phi.clone() * 2.0); + let leaf_gate = CircuitGate::with_signature( + "leaf", + FrozenCircuit::new(leaf), + ["unused".to_string(), "phi".to_string(), "theta".to_string()], + ) + .unwrap(); + + let mut middle = Circuit::new(1); + middle + .append( + Instruction::CircuitGate(Box::new(leaf_gate)), + [q0], + [ + ParameterValue::from(11.0), + ParameterValue::from(theta.clone() + 1.0), + ParameterValue::from(phi.clone() - 0.5), + ], + None, + ) + .unwrap(); + let middle_gate = CircuitGate::with_signature( + "middle", + FrozenCircuit::new(middle), + ["phi".to_string(), "theta".to_string()], + ) + .unwrap(); + let mut circuit = Circuit::new(1); + circuit + .append( + Instruction::CircuitGate(Box::new(middle_gate)), + [q0], + [ + ParameterValue::from(theta.clone()), + ParameterValue::from(phi.clone()), + ], + None, + ) + .unwrap(); + + let mut expected = Circuit::new(1); + expected.rx(q0, theta.clone() - 0.5).unwrap(); + expected.rz(q0, phi.clone() + 1.0).unwrap(); + expected.set_global_phase(theta - 0.5 + (phi + 1.0) * 2.0); + let expanded = expand_definitions(&circuit).unwrap(); + for (theta, phi) in [(0.2, 0.8), (-0.4, 0.1)] { + let bindings = Some(HashMap::from([("theta", theta), ("phi", phi)])); + let expected_matrix = + circuit_to_matrix(&expected.assign_parameters(&bindings).unwrap(), None).unwrap(); + for actual in [&circuit, &expanded] { + let bound = actual.assign_parameters(&bindings).unwrap(); + assert_matrix_approx_eq( + &circuit_to_matrix(&bound, None).unwrap(), + &expected_matrix, + 1e-12, + ); + } + } + } + #[test] fn uses_simultaneous_parameter_substitution() { let mut inner = Circuit::new(1); @@ -894,15 +1090,27 @@ mod tests { #[test] fn expands_definitions_in_control_flow_body_with_body_local_phase() { let mut inner = Circuit::new(1); - inner.set_global_phase(Parameter::from(0.5)); + inner.set_global_phase(Parameter::symbol("phase")); inner.x(Qubit::new(0)).unwrap(); - let gate = inner.to_gate("phase_x").unwrap(); + let gate = CircuitGate::with_signature( + "phase_x", + FrozenCircuit::new(inner), + ["unused".to_string(), "phase".to_string()], + ) + .unwrap(); let mut circuit = Circuit::new(2); circuit .if_else( ClassicalExpr::bool_literal(true), - |body| body.append(gate, [Qubit::new(1)], [], None), + |body| { + body.append( + Instruction::CircuitGate(Box::new(gate)), + [Qubit::new(1)], + [ParameterValue::from(11.0), ParameterValue::from(0.5)], + None, + ) + }, |_body| Ok(()), ) .unwrap(); @@ -920,6 +1128,14 @@ mod tests { then_body[0].instruction, Instruction::Standard(StandardGate::GPhase) )); + assert!( + (op_param(&expanded, &then_body[0].params[0]) + .evaluate(&None) + .unwrap() + - 0.5) + .abs() + < 1e-12 + ); assert!(matches!( then_body[1].instruction, Instruction::Standard(StandardGate::X) diff --git a/crates/cqlib-core/src/compile/transform/decompose/mod.rs b/crates/cqlib-core/src/compile/transform/decompose/mod.rs index c356a7dd..f33affe8 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/mod.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/mod.rs @@ -19,7 +19,7 @@ //! Use this first for [`CircuitGate`](crate::circuit::gate::CircuitGate) and //! circuit-backed [`UnitaryGate`](crate::circuit::UnitaryGate) operations. //! - [`unitary`] synthesizes remaining custom `UnitaryGate` operations from -//! fixed numeric matrices. It currently supports one- and two-qubit matrices. +//! fixed numeric matrices. Larger matrices use recursive [`block_zxz`] synthesis. //! - [`mc_gate`] provides explicit algorithmic synthesis primitives for //! multi-controlled gates, plus the circuit-level resource-aware //! `decompose_mc_gates` entry point. @@ -44,11 +44,15 @@ //! Directed-coupling legalization and scheduling are separate compiler //! concerns. +pub mod block_zxz; pub mod definition; pub mod mc_gate; pub mod rule; pub mod unitary; +pub use block_zxz::{ + BlockZxzDecomposeOptions, decompose_block_zxz, decompose_block_zxz_with_options, +}; pub use definition::{DecomposeDefinitions, expand_definitions}; pub use mc_gate::{ DecomposeMcGates, McGateDecomposeConfig, decompose_mc_gates, decompose_mc_gates_with_rule_stats, diff --git a/crates/cqlib-core/src/compile/transform/decompose/rule.rs b/crates/cqlib-core/src/compile/transform/decompose/rule.rs index 7e22d72f..d3920e5a 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/rule.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/rule.rs @@ -22,6 +22,7 @@ use crate::circuit::{ Instruction, Parameter, ParameterValue, Qubit, StandardGate, ValueInstruction, ValueOperation, }; use crate::compile::CompilerError; +use crate::compile::transform::decompose::BlockZxzDecomposeOptions; use crate::compile::transform::decompose::unitary::TwoQubitSynthesisTarget; use crate::compile::transform::target_basis::TargetBasisSignature; use ndarray::Array2; @@ -157,6 +158,11 @@ pub struct NumericUnitaryRuleRequest<'a> { #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum NumericUnitarySynthesisKey { OneQubit, + /// Matrix-backed multi-qubit synthesis, including its absolute tolerance. + BlockZxz { + options: BlockZxzDecomposeOptions, + atol_bits: u64, + }, TwoQubit { target_basis: Option, fallback_pauli: bool, @@ -624,4 +630,64 @@ mod tests { } ); } + + #[test] + fn block_zxz_cache_keys_include_each_option_tolerance_and_matrix_bits() { + let matrix = Array2::::eye(8); + let phased = &matrix * Complex64::from_polar(1., 0.23); + let options = BlockZxzDecomposeOptions::default(); + let request = |matrix, options, atol: f64| NumericUnitaryRuleRequest { + num_qubits: 3, + matrix, + synthesis_key: NumericUnitarySynthesisKey::BlockZxz { + options, + atol_bits: atol.to_bits(), + }, + }; + let qubits = [Qubit::new(2), Qubit::new(0), Qubit::new(1)]; + let mut cache = DecompositionRuleCache::default(); + cache + .insert_numeric_unitary(request(&matrix, options, 1e-10), &qubits, &[], 0.37) + .unwrap(); + for different in [ + request( + &matrix, + BlockZxzDecomposeOptions { + opt_a1: false, + ..options + }, + 1e-10, + ), + request( + &matrix, + BlockZxzDecomposeOptions { + opt_a2: false, + ..options + }, + 1e-10, + ), + request( + &matrix, + BlockZxzDecomposeOptions { + opt_a2_force: true, + ..options + }, + 1e-10, + ), + request(&matrix, options, 1e-11), + request(&phased, options, 1e-10), + ] { + assert!( + cache + .instantiate_numeric_unitary(different, &qubits) + .unwrap() + .is_none() + ); + } + let (_, phase) = cache + .instantiate_numeric_unitary(request(&matrix, options, 1e-10), &qubits) + .unwrap() + .unwrap(); + assert_eq!(phase, 0.37); + } } diff --git a/crates/cqlib-core/src/compile/transform/decompose/unitary/decompose.rs b/crates/cqlib-core/src/compile/transform/decompose/unitary/decompose.rs index 6bf63b8e..eb2c732c 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/unitary/decompose.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/unitary/decompose.rs @@ -13,7 +13,7 @@ //! Numeric matrix-backed `UnitaryGate` synthesis. //! //! This is the circuit-facing entry point for [`super`]. It rebuilds a source -//! circuit while replacing remaining matrix-backed one- and two-qubit +//! circuit while replacing remaining matrix-backed //! `UnitaryGate` operations with standard-gate sequences. Definition expansion //! is expected to run first: a unitary gate without a matrix representation is //! rejected with an error directing the caller to expand definitions. @@ -31,16 +31,17 @@ //! //! This pass deliberately leaves ordinary standard gates such as `RX` and `RZ` //! unchanged. Target-basis rewrites own that behavior. Its supported input -//! contract requires finite numeric one- or two-qubit unitary matrices. It +//! contract requires finite numeric unitary matrices. It //! rejects unresolved or non-finite unitary parameters, missing matrices, -//! invalid matrix shapes, and unitary gates acting on three or more qubits. +//! and invalid matrix shapes. use super::DeviceTwoQubitSynthesisContext; use super::two_qubit_kak::kak_decompose; use super::unitary_1q::{OneQubitUnitaryDecomposition, synthesize_numeric_1q_unitary}; use super::unitary_2q::{ - TwoQubitSynthesisRequest, TwoQubitSynthesisTarget, plan_numeric_2q_unitary_for_device_from_kak, - plan_numeric_2q_unitary_from_kak, select_validated_device_unitary_candidate_from_kak, + TwoQubitSynthesisCandidate, TwoQubitSynthesisRequest, TwoQubitSynthesisTarget, + plan_numeric_2q_unitary_for_device_from_kak, plan_numeric_2q_unitary_from_kak, + select_validated_device_unitary_candidate_from_kak, select_validated_numeric_2q_candidate_from_kak, }; use crate::circuit::{ @@ -54,6 +55,9 @@ use crate::compile::transform::decompose::rule::{ DecompositionRuleCache, DecompositionRuleStats, NumericUnitaryRuleRequest, NumericUnitarySynthesisKey, }; +use crate::compile::transform::decompose::{ + BlockZxzDecomposeOptions, decompose_block_zxz_with_options, +}; use crate::compile::transform::rebuild::{CircuitRebuildContext, ClassicalRemap}; use crate::compile::transform::transformer::{PassApplicability, WorkflowPass}; use crate::compile::transform::{CircuitAnalysis, TransformOutcome, Transformer}; @@ -64,8 +68,6 @@ use std::borrow::Cow; use std::collections::HashMap; const SYNTHESIS_NAME: &str = "decompose.unitary"; -const ANGLE_EPS: f64 = 1e-12; -const PHASE_EPS: f64 = 1e-12; /// Configuration for circuit-level matrix-backed `UnitaryGate` synthesis. #[derive(Clone, Debug, PartialEq, Eq)] @@ -75,6 +77,8 @@ pub struct UnitaryDecomposeConfig { /// Whether matrix-backed `UnitaryGate` operations inside control-flow /// bodies should be synthesized recursively. pub recurse_control_flow: bool, + /// Optimization switches applied to three-or-more-qubit Block-ZXZ synthesis. + pub block_zxz_options: BlockZxzDecomposeOptions, } impl Default for UnitaryDecomposeConfig { @@ -82,6 +86,7 @@ impl Default for UnitaryDecomposeConfig { Self { two_qubit_target: TwoQubitSynthesisTarget::default(), recurse_control_flow: true, + block_zxz_options: BlockZxzDecomposeOptions::default(), } } } @@ -167,15 +172,16 @@ impl Transformer for DecomposeUnitaries { /// /// One-qubit matrices are emitted as [`StandardGate::U`] operations when a /// non-trivial local gate remains. Two-qubit matrices are emitted according to -/// [`UnitaryDecomposeConfig::two_qubit_target`]. Synthesized scalar phases are -/// preserved either as circuit global phase or, within recursively processed +/// [`UnitaryDecomposeConfig::two_qubit_target`]. Larger matrices use recursive +/// Block-ZXZ synthesis. Scalar phases are preserved as circuit global phase or, +/// within recursively processed /// control-flow bodies, as explicit [`StandardGate::GPhase`] operations. /// /// # Errors /// /// Returns [`CompilerError`] if a matrix-backed `UnitaryGate` has non-fixed /// parameters, no matrix representation, unsupported arity, invalid qubit -/// arity, or if the numeric 1q/2q synthesis primitive rejects the matrix. +/// arity, or if the numeric synthesis backend rejects the matrix. pub fn decompose_unitaries( circuit: &Circuit, config: UnitaryDecomposeConfig, @@ -264,7 +270,7 @@ impl<'a> UnitaryDecomposer<'a> { let mut operations = Vec::with_capacity(self.source.operations().len()); let phase_delta = self.apply_sequence(self.source.operations(), &root_classical, &mut operations)?; - if phase_delta.abs() > PHASE_EPS { + if phase_delta != 0.0 { self.top_phase = self.top_phase + Parameter::from(phase_delta); } let circuit = self @@ -408,7 +414,7 @@ impl<'a> UnitaryDecomposer<'a> { let mut body = Vec::with_capacity(source_body.len()); if self.config.recurse_control_flow { let phase_delta = self.apply_sequence(source_body, classical_remap, &mut body)?; - if phase_delta.abs() > PHASE_EPS { + if phase_delta != 0.0 { body.insert( 0, ValueOperation { @@ -461,22 +467,74 @@ impl<'a> UnitaryDecomposer<'a> { } let matrix = self.numeric_matrix_for_gate(gate, operation)?; - match gate.num_qubits() { + if let [first, second] = operation.qubits.as_slice() + && let Some(context) = self.device_context.as_ref() + { + let qubits = [*first, *second]; + let cache_key = DeviceUnitaryCacheKey { + matrix_bits: matrix + .iter() + .map(|value| (value.re.to_bits(), value.im.to_bits())) + .collect(), + ordered_qargs: qubits, + }; + if let Some(decomposition) = self.device_cache.get(&cache_key) { + return Ok(decomposition.clone()); + } + let decomp = kak_decompose(matrix.as_ref())?; + let candidates = plan_numeric_2q_unitary_for_device_from_kak( + matrix.as_ref(), + qubits, + context, + &decomp, + )?; + let candidate = select_validated_device_unitary_candidate_from_kak( + matrix.as_ref(), + qubits, + context, + &decomp, + candidates, + )? + .ok_or_else(|| CompilerError::TransformFailed { + name: SYNTHESIS_NAME, + reason: format!( + "no exact device-aware two-qubit synthesis candidate for UnitaryGate '{}'", + gate.label() + ), + })?; + let decomposition = Decomposition { + operations: candidate.operations, + phase_delta: candidate.global_phase, + }; + self.device_cache.insert(cache_key, decomposition.clone()); + return Ok(decomposition); + } + + let options = self.config.block_zxz_options; + let atol = 1e-10_f64; + let request = NumericUnitaryRuleRequest { + num_qubits: gate.num_qubits(), + matrix: matrix.as_ref(), + synthesis_key: match gate.num_qubits() { + 1 => NumericUnitarySynthesisKey::one_qubit(), + 2 => NumericUnitarySynthesisKey::two_qubit(&self.config.two_qubit_target), + _ => NumericUnitarySynthesisKey::BlockZxz { + options, + atol_bits: atol.to_bits(), + }, + }, + }; + if let Some((operations, phase_delta)) = self + .rule_cache + .instantiate_numeric_unitary(request.clone(), &operation.qubits)? + { + return Ok(Decomposition { + operations, + phase_delta, + }); + } + let decomposition = match gate.num_qubits() { 1 => { - let request = NumericUnitaryRuleRequest { - num_qubits: gate.num_qubits(), - matrix: matrix.as_ref(), - synthesis_key: NumericUnitarySynthesisKey::one_qubit(), - }; - if let Some((operations, phase_delta)) = self - .rule_cache - .instantiate_numeric_unitary(request.clone(), &operation.qubits)? - { - return Ok(Decomposition { - operations, - phase_delta, - }); - } let OneQubitUnitaryDecomposition { theta, phi, @@ -492,7 +550,9 @@ impl<'a> UnitaryDecomposer<'a> { } })?; let mut operations = Vec::new(); - if theta.abs() > ANGLE_EPS || phi.abs() > ANGLE_EPS || lambda.abs() > ANGLE_EPS { + // Each cached template may be replayed many times; small but + // nonzero rotations accumulate coherently across call sites. + if theta != 0.0 || phi != 0.0 || lambda != 0.0 { operations.push(ValueOperation { instruction: ValueInstruction::from_instruction(Instruction::Standard( StandardGate::U, @@ -506,75 +566,13 @@ impl<'a> UnitaryDecomposer<'a> { label: None, }); } - let decomposition = Decomposition { + Decomposition { operations, phase_delta: global_phase, - }; - self.rule_cache.insert_numeric_unitary( - request, - &operation.qubits, - &decomposition.operations, - decomposition.phase_delta, - )?; - Ok(decomposition) + } } 2 => { let qubits = [operation.qubits[0], operation.qubits[1]]; - if let Some(context) = self.device_context.as_ref() { - let cache_key = DeviceUnitaryCacheKey { - matrix_bits: matrix - .iter() - .map(|value| (value.re.to_bits(), value.im.to_bits())) - .collect(), - ordered_qargs: qubits, - }; - if let Some(decomposition) = self.device_cache.get(&cache_key) { - return Ok(decomposition.clone()); - } - let decomp = kak_decompose(matrix.as_ref())?; - let candidates = plan_numeric_2q_unitary_for_device_from_kak( - matrix.as_ref(), - qubits, - context, - &decomp, - )?; - let candidate = select_validated_device_unitary_candidate_from_kak( - matrix.as_ref(), - qubits, - context, - &decomp, - candidates, - )? - .ok_or_else(|| CompilerError::TransformFailed { - name: SYNTHESIS_NAME, - reason: format!( - "no exact device-aware two-qubit synthesis candidate for UnitaryGate '{}'", - gate.label() - ), - })?; - let decomposition = Decomposition { - operations: candidate.operations, - phase_delta: candidate.global_phase, - }; - self.device_cache.insert(cache_key, decomposition.clone()); - return Ok(decomposition); - } - let request = NumericUnitaryRuleRequest { - num_qubits: gate.num_qubits(), - matrix: matrix.as_ref(), - synthesis_key: NumericUnitarySynthesisKey::two_qubit( - &self.config.two_qubit_target, - ), - }; - if let Some((operations, phase_delta)) = self - .rule_cache - .instantiate_numeric_unitary(request.clone(), &operation.qubits)? - { - return Ok(Decomposition { - operations, - phase_delta, - }); - } let decomp = kak_decompose(matrix.as_ref())?; let candidates = plan_numeric_2q_unitary_from_kak( TwoQubitSynthesisRequest { @@ -598,31 +596,43 @@ impl<'a> UnitaryDecomposer<'a> { gate.label() ), })?; - let crate::compile::transform::decompose::unitary::TwoQubitSynthesisCandidate { + let TwoQubitSynthesisCandidate { operations, global_phase, .. } = candidate; - let decomposition = Decomposition { + Decomposition { operations, phase_delta: global_phase, - }; - self.rule_cache.insert_numeric_unitary( - request, - &operation.qubits, - &decomposition.operations, - decomposition.phase_delta, - )?; - Ok(decomposition) + } } - other => Err(CompilerError::TransformFailed { - name: SYNTHESIS_NAME, - reason: format!( - "3q+ UnitaryGate synthesis is not supported yet; gate '{}' has {other} qubits", - gate.label() - ), - }), - } + _ => { + let circuit = decompose_block_zxz_with_options(matrix.as_ref(), atol, &options)?; + let phase_delta = circuit.global_phase().evaluate(&None).map_err(|e| { + CompilerError::InvariantViolation(format!("non-numeric Block-ZXZ phase: {e}")) + })?; + let mut operations = Vec::with_capacity(circuit.operations().len()); + for i in 0..circuit.operations().len() { + let mut op = circuit.index(i)?; + // UnitaryGate arguments are MSB-first; local circuit q0 is the LSB. + for q in &mut op.qubits { + *q = operation.qubits[operation.qubits.len() - 1 - q.index()]; + } + operations.push(op); + } + Decomposition { + operations, + phase_delta, + } + } + }; + self.rule_cache.insert_numeric_unitary( + request, + &operation.qubits, + &decomposition.operations, + decomposition.phase_delta, + )?; + Ok(decomposition) } fn numeric_matrix_for_gate<'gate>( @@ -731,6 +741,167 @@ mod tests { } } + #[test] + fn weyl_boundary_unitary_gate_decomposition_preserves_phase_and_device_constraints() { + use crate::compile::test_utils::{build_device_synthesis_context, kak_boundary_matrix}; + use crate::compile::transform::decompose::unitary::DeviceSynthesisPlacement; + use crate::device::Device; + + let gate = UnitaryGate::new("boundary", 2, 0) + .with_matrix(kak_boundary_matrix()) + .unwrap(); + let mut source = Circuit::new(2); + source + .unitary(gate.clone(), vec![Qubit::new(1), Qubit::new(0)]) + .unwrap(); + source + .unitary(gate, vec![Qubit::new(1), Qubit::new(0)]) + .unwrap(); + source.set_global_phase(Parameter::from(0.37)); + let expected = circuit_to_matrix(&source, None).unwrap(); + + for gate in [ + StandardGate::CX, + StandardGate::CY, + StandardGate::CZ, + StandardGate::RZZ, + ] { + let config = config_for_native_2q(gate); + let (generic, stats) = + decompose_unitaries_with_rule_stats(&source, config.clone()).unwrap(); + assert_eq!(stats.hits, 1); + assert_eq!(stats.misses, 1); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&generic.circuit, None).unwrap(), + epsilon = 1e-9 + ); + + let device = Device::bidirectional_line("boundary", 2) + .unwrap() + .with_native_gates( + config + .two_qubit_target + .native_1q() + .iter() + .copied() + .chain([gate]) + .map(Instruction::Standard) + .collect(), + ) + .unwrap(); + // Matrix-backed gates are synthesized before physical routing. + let context = build_device_synthesis_context( + &device, + &source, + DeviceSynthesisPlacement::PreLayoutEnvelope, + ) + .unwrap(); + let result = DecomposeUnitaries::new_device_aware(config.clone(), context) + .transform_resolved(&source, None) + .unwrap_or_else(|error| panic!("gate={gate:?}: {error}")); + assert!(result.changed); + assert!( + result + .circuit + .operations() + .iter() + .all(|op| match op.instruction { + Instruction::Standard(g) => g.num_qubits() == 1 || g == gate, + _ => false, + }) + ); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&result.circuit, None).unwrap(), + epsilon = 1e-9 + ); + } + } + + #[test] + fn weyl_boundary_does_not_bypass_unsupported_device_interactions() { + use crate::compile::test_utils::{build_device_synthesis_context, kak_boundary_matrix}; + use crate::compile::transform::decompose::unitary::DeviceSynthesisPlacement; + use crate::device::Device; + let mut source = Circuit::new(2); + source + .unitary( + UnitaryGate::new("boundary", 2, 0) + .with_matrix(kak_boundary_matrix()) + .unwrap(), + vec![Qubit::new(0), Qubit::new(1)], + ) + .unwrap(); + let device = Device::bidirectional_line("no-entangler", 2) + .unwrap() + .with_native_gates(vec![Instruction::Standard(StandardGate::U)]) + .unwrap(); + let context = build_device_synthesis_context( + &device, + &source, + DeviceSynthesisPlacement::PreLayoutEnvelope, + ) + .unwrap(); + let error = DecomposeUnitaries::new_device_aware(Default::default(), context) + .transform_resolved(&source, None) + .unwrap_err(); + assert!( + error + .to_string() + .contains("no exact device-aware two-qubit synthesis candidate") + ); + } + + #[test] + fn weyl_boundary_phase_stays_inside_classical_control_body() { + use crate::compile::test_utils::kak_boundary_matrix; + let gate = UnitaryGate::new("boundary", 2, 0) + .with_matrix(kak_boundary_matrix()) + .unwrap(); + let mut expected_body = Circuit::new(2); + expected_body + .unitary(gate.clone(), vec![Qubit::new(0), Qubit::new(1)]) + .unwrap(); + let mut source = Circuit::new(2); + source + .if_else( + ClassicalExpr::bool_literal(true), + |body| { + body.append( + Instruction::UnitaryGate(Box::new(gate)), + [Qubit::new(0), Qubit::new(1)], + [], + None, + ) + }, + |_| Ok(()), + ) + .unwrap(); + let output = decompose_unitaries(&source, Default::default()).unwrap(); + assert!(output.global_phase().is_zero()); + let Instruction::ClassicalControl(ClassicalControlOp::If(control)) = + &output.operations()[0].instruction + else { + panic!("expected if body") + }; + let mut body = Circuit::new(2); + for op in control.then_body().operations() { + let params = op + .params + .iter() + .map(|param| output.parameter_value(param).unwrap()) + .collect::>(); + body.append(op.instruction.clone(), op.qubits.clone(), params, None) + .unwrap(); + } + assert_abs_diff_eq!( + circuit_to_matrix(&body, None).unwrap(), + circuit_to_matrix(&expected_body, None).unwrap(), + epsilon = 1e-9 + ); + } + fn operation_parameter(circuit: &Circuit, operation: &Operation, position: usize) -> Parameter { match operation.params.get(position) { Some(CircuitParam::Fixed(value)) => Parameter::from(*value), @@ -1475,16 +1646,28 @@ mod tests { } #[test] - fn rejects_three_qubit_unitary_gate() { - let gate = UnitaryGate::new("custom_3q", 3, 0) - .with_matrix(Array2::eye(8)) - .unwrap(); - let mut circuit = Circuit::new(3); - circuit - .unitary(gate, vec![Qubit::new(0), Qubit::new(1), Qubit::new(2)]) - .unwrap(); - - let err = decompose_unitaries(&circuit, UnitaryDecomposeConfig::default()).unwrap_err(); - assert!(err.to_string().contains("not supported yet")); + fn cached_sub_picoradian_one_qubit_rotations_accumulate() { + let phase = 4e-13; + let mut u = Array2::eye(2); + u[[1, 1]] = Complex64::from_polar(1., phase); + let gate = UnitaryGate::new("weak phase", 1, 0).with_matrix(u).unwrap(); + let mut circuit = Circuit::new(1); + for _ in 0..512 { + circuit.unitary(gate.clone(), vec![Qubit::new(0)]).unwrap(); + } + let (out, stats) = + decompose_unitaries_with_rule_stats(&circuit, Default::default()).unwrap(); + assert_eq!((stats.hits, stats.misses), (511, 1)); + let actual = out.circuit.to_matrix(None).unwrap(); + let expected = Array2::from_diag(&array![ + Complex64::ONE, + Complex64::from_polar(1., 512. * phase) + ]); + let error = actual + .iter() + .zip(&expected) + .map(|(a, b)| (a - b).norm()) + .fold(0., f64::max); + assert!(error < 1e-14, "maximum matrix error {error:e}"); } } diff --git a/crates/cqlib-core/src/compile/transform/decompose/unitary/mod.rs b/crates/cqlib-core/src/compile/transform/decompose/unitary/mod.rs index ea59dd09..6c665653 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/unitary/mod.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/unitary/mod.rs @@ -19,10 +19,10 @@ //! //! # Supported inputs //! -//! The circuit-facing pass supports fixed numeric one- and two-qubit unitary +//! The circuit-facing pass supports fixed numeric unitary //! matrices. A parameterized matrix is supported only after every argument at //! the call site resolves to a finite numeric value. Three-qubit and larger -//! matrices are rejected explicitly. +//! matrices use [`super::block_zxz`]. //! //! This module does not expand circuit-backed definitions or adapt gates to //! hardware topology. It also does not perform target-basis lowering itself; @@ -75,3 +75,4 @@ pub(crate) use device_synthesis::{ DeviceContextCostFailure, DevicePhysicalCost, DevicePreLayoutEvaluation, DeviceSynthesisPlacement, DeviceTwoQubitSynthesisContext, }; +pub(crate) use unitary_2q::TWO_QUBIT_EXACT_TOLERANCE; diff --git a/crates/cqlib-core/src/compile/transform/decompose/unitary/two_qubit_kak.rs b/crates/cqlib-core/src/compile/transform/decompose/unitary/two_qubit_kak.rs index c57807f3..3c6f7ebe 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/unitary/two_qubit_kak.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/unitary/two_qubit_kak.rs @@ -24,7 +24,9 @@ //! //! The returned coordinates satisfy the Weyl chamber convention //! `pi/4 >= a >= b >= |c|`, with the additional boundary convention that -//! `c >= 0` when `a = pi/4`. The compiler-facing lowering lives in +//! `c >= 0` when `a = pi/4`. Coordinates within floating-point roundoff of +//! that wall are normalized to `a = pi/4` before selecting its representative. +//! The compiler-facing lowering lives in //! `unitary_2q.rs`; this file owns only the numerical decomposition contract. //! //! The implementation validates finite 4x4 input, the intermediate symmetric @@ -49,6 +51,10 @@ const UNITARY_EPS: f64 = 1e-8; const RECONSTRUCTION_EPS: f64 = 1e-7; const AUTONNE_EPS: f64 = 10.0 * UNITARY_EPS; const KRON_RANK_EPS: f64 = 1e-8; +// Angle extraction and folding accumulate a small number of f64 rounding +// errors. This allowance is deliberately independent of input unitarity and +// reconstruction tolerances: genuine interior coordinates may have c < 0. +const WEYL_BOUNDARY_EPS: f64 = 32.0 * f64::EPSILON; static B_RAW: [[Complex64; 4]; 4] = [ [c(1.0, 0.0), c(0.0, 1.0), c(0.0, 0.0), c(0.0, 0.0)], @@ -301,7 +307,7 @@ pub fn kak_decompose(matrix: &Array2) -> Result) -> Result Result<(), CompilerError> { let eps = UNITARY_EPS; if a < -eps || b < -eps { @@ -337,9 +364,11 @@ fn validate_weyl_chamber(a: f64, b: f64, c: f64) -> Result<(), CompilerError> { c.abs() ))); } - if (a - FRAC_PI_4).abs() < eps && c < -eps { + // Boundary normalization sets a exactly to this constant. An epsilon band + // here would incorrectly reject valid interior points with negative c. + if a == FRAC_PI_4 && c < 0.0 { return Err(kak_failed(format!( - "Weyl chamber violation: a=pi/4 but c={c} < 0" + "Weyl chamber violation: a={a} on pi/4 wall but c={c} < 0" ))); } Ok(()) @@ -768,6 +797,7 @@ fn decompose_two_qubit_product_gate( #[cfg(test)] mod tests { use super::*; + use crate::compile::test_utils::kak_boundary_matrix; use approx::assert_abs_diff_eq; use ndarray::linalg::kron; @@ -813,6 +843,76 @@ mod tests { decomp.c, decomp.b ); + if decomp.a == FRAC_PI_4 { + assert!( + decomp.c >= 0.0, + "negative c={} on the a=pi/4 wall", + decomp.c + ); + } + } + + #[test] + fn weyl_boundary_reported_matrix_preserves_full_reconstruction() { + for phase in [0.0, -1.1, FRAC_PI_4, FRAC_PI_2, PI, 2.7] { + let matrix = + kak_boundary_matrix().mapv(|value| value * Complex64::from_polar(1.0, phase)); + let decomp = kak_decompose(&matrix).unwrap(); + assert_eq!(decomp.a, FRAC_PI_4); + assert!(decomp.c > 0.0); + assert_weyl_chamber(&decomp); + validate_local_su2(&decomp).unwrap(); + assert!(max_entry_diff(&matrix, &reconstructed_from_kak(&decomp)) < 1e-12); + } + } + + #[test] + fn weyl_boundary_distinguishes_roundoff_from_interior_coordinates() { + let left = kron( + &StandardGate::RY.matrix(&[0.7]).unwrap(), + &StandardGate::RZ.matrix(&[-0.4]).unwrap(), + ); + let right = kron( + &StandardGate::RX.matrix(&[-1.1]).unwrap(), + &StandardGate::RY.matrix(&[0.3]).unwrap(), + ); + for delta in [0.0, 4.0 * f64::EPSILON, 1e-12, 1e-10, 5e-9, 2e-8] { + for sign in [-1.0, 1.0] { + for c in [-0.03, 0.03, -1e-12, 1e-12] { + let a = FRAC_PI_4 + sign * delta; + let rxx = StandardGate::RXX.matrix(&[-2.0 * a]).unwrap(); + let ryy = StandardGate::RYY.matrix(&[-0.4]).unwrap(); + let rzz = StandardGate::RZZ.matrix(&[-2.0 * c]).unwrap(); + let matrix = left + .dot(&rxx.dot(&ryy.dot(&rzz.dot(&right)))) + .mapv(|value| value * Complex64::from_polar(1.0, 0.37)); + let decomp = kak_decompose(&matrix).unwrap(); + assert_weyl_chamber(&decomp); + validate_local_su2(&decomp).unwrap(); + if delta <= 4.0 * f64::EPSILON { + assert_eq!(decomp.a, FRAC_PI_4); + assert!(decomp.c >= 0.0); + } else { + assert!(decomp.a < FRAC_PI_4); + let expected_c = if sign < 0.0 { c } else { -c }; + assert_eq!(decomp.c.is_sign_negative(), expected_c.is_sign_negative()); + assert!((decomp.a - (FRAC_PI_4 - delta)).abs() < 1e-14); + } + assert!(max_entry_diff(&matrix, &reconstructed_from_kak(&decomp)) < 1e-12); + } + } + } + } + + #[test] + fn weyl_boundary_validator_accepts_negative_c_in_the_interior() { + for distance in [1e-12, 1e-10, 5e-9, 2e-8] { + validate_weyl_chamber(FRAC_PI_4 - distance, 0.2, -0.03).unwrap(); + } + assert!(validate_weyl_chamber(FRAC_PI_4, 0.2, -0.03).is_err()); + assert!(validate_weyl_chamber(FRAC_PI_4, 0.2, -1e-12).is_err()); + assert!(validate_weyl_chamber(FRAC_PI_4 + 1e-6, 0.2, 0.03).is_err()); + assert!(validate_weyl_chamber(0.3, 0.2, 0.25).is_err()); } #[test] diff --git a/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q.rs b/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q.rs index 21f50016..b67b18db 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q.rs @@ -48,8 +48,8 @@ use num_complex::Complex64; use std::f64::consts::{FRAC_1_SQRT_2, FRAC_PI_2, PI}; use std::sync::{Arc, LazyLock}; -const ANGLE_EPS: f64 = 1e-12; -const TWO_QUBIT_EXACT_TOLERANCE: f64 = 1e-10; +const ANGLE_EPS: f64 = 64.0 * f64::EPSILON; +pub(crate) const TWO_QUBIT_EXACT_TOLERANCE: f64 = 1e-10; /// Output basis used for two-qubit unitary synthesis. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -1098,15 +1098,15 @@ pub(crate) fn minimum_constructive_entanglers( fn minimum_pauli_entanglers(decomp: &KakDecomposition) -> usize { [decomp.a, decomp.b, decomp.c] .into_iter() - .filter(|value| value.abs() > TWO_QUBIT_EXACT_TOLERANCE) + .filter(|value| value.abs() > ANGLE_EPS) .count() } fn minimum_cx_family_entanglers(decomp: &KakDecomposition) -> usize { - let near_zero = |value: f64| value.abs() <= TWO_QUBIT_EXACT_TOLERANCE; + let near_zero = |value: f64| value.abs() <= ANGLE_EPS; if near_zero(decomp.a) && near_zero(decomp.b) && near_zero(decomp.c) { 0 - } else if (decomp.a - std::f64::consts::FRAC_PI_4).abs() <= TWO_QUBIT_EXACT_TOLERANCE + } else if (decomp.a - std::f64::consts::FRAC_PI_4).abs() <= ANGLE_EPS && near_zero(decomp.b) && near_zero(decomp.c) { @@ -2011,12 +2011,41 @@ mod tests { decomp.b = 0.17; assert_eq!(minimum_cx_family_entanglers(&decomp), 2); - decomp.c = 2.0 * TWO_QUBIT_EXACT_TOLERANCE; + decomp.c = 2.0 * ANGLE_EPS; assert_eq!(minimum_cx_family_entanglers(&decomp), 3); - decomp.c = 0.5 * TWO_QUBIT_EXACT_TOLERANCE; + decomp.c = 0.5 * ANGLE_EPS; assert_eq!(minimum_cx_family_entanglers(&decomp), 2); } + #[test] + fn cx_family_backends_preserve_sub_tolerance_weak_xx_interaction() { + let angle = 9e-11_f64; + let u = Array2::from_shape_fn((4, 4), |(i, j)| match i ^ j { + 0 => Complex64::from(angle.cos()), + 3 => Complex64::i() * angle.sin(), + _ => Complex64::ZERO, + }); + let qubits = [Qubit::new(1), Qubit::new(0)]; + for basis in [ + TwoQubitUnitaryDecomposeBasis::Cx, + TwoQubitUnitaryDecomposeBasis::Cy, + TwoQubitUnitaryDecomposeBasis::Cz, + ] { + let synth = synthesize_numeric_2q_unitary(&u, qubits, basis).unwrap(); + let actual = + value_operations_matrix(&synth.operations, synth.global_phase, qubits).unwrap(); + let max_err = actual + .iter() + .zip(u.iter()) + .map(|(a, b)| (a - b).norm()) + .fold(0.0_f64, f64::max); + assert!( + max_err < 1e-13, + "basis {basis:?} dropped weak XX interaction: max_err={max_err:e}" + ); + } + } + #[test] fn fixed_matrix_product_matches_dense_reference_for_mixed_orientations() { let q0 = Qubit::new(3); diff --git a/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q_test.rs b/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q_test.rs index bebe41fe..96056123 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q_test.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/unitary/unitary_2q_test.rs @@ -18,6 +18,66 @@ use super::unitary_2q::{ }; use crate::circuit::{Instruction, Qubit, StandardGate, ValueInstruction}; +#[test] +fn weyl_boundary_all_backends_preserve_phase_and_qubit_order() { + use super::unitary_2q::{TwoQubitSynthesisCandidate, synthesize_numeric_2q_unitary}; + use crate::compile::test_utils::kak_boundary_matrix; + use num_complex::Complex64; + for phase in [0.0, 0.37] { + let matrix = kak_boundary_matrix().mapv(|value| value * Complex64::from_polar(1.0, phase)); + for qubits in [ + [Qubit::new(0), Qubit::new(1)], + [Qubit::new(3), Qubit::new(1)], + ] { + for backend in [ + TwoQubitUnitaryDecomposeBasis::Cx, + TwoQubitUnitaryDecomposeBasis::Cy, + TwoQubitUnitaryDecomposeBasis::Cz, + TwoQubitUnitaryDecomposeBasis::Rzz, + TwoQubitUnitaryDecomposeBasis::PauliRotations, + ] { + let result = synthesize_numeric_2q_unitary(&matrix, qubits, backend).unwrap(); + let candidate = TwoQubitSynthesisCandidate { + backend, + operations: result.operations, + global_phase: result.global_phase, + cost: Default::default(), + }; + validate_numeric_2q_candidate(&matrix, qubits, &candidate).unwrap(); + assert!( + candidate + .operations + .iter() + .all(|op| op.qubits.iter().all(|q| qubits.contains(q))) + ); + assert!( + candidate + .operations + .iter() + .filter(|op| op.qubits.len() == 2) + .all(|op| { + let ValueInstruction::Instruction(Instruction::Standard(gate)) = + op.instruction + else { + return false; + }; + match backend { + TwoQubitUnitaryDecomposeBasis::Cx => gate == StandardGate::CX, + TwoQubitUnitaryDecomposeBasis::Cy => gate == StandardGate::CY, + TwoQubitUnitaryDecomposeBasis::Cz => gate == StandardGate::CZ, + TwoQubitUnitaryDecomposeBasis::Rzz => gate == StandardGate::RZZ, + TwoQubitUnitaryDecomposeBasis::PauliRotations => matches!( + gate, + StandardGate::RXX | StandardGate::RYY | StandardGate::RZZ + ), + } + }) + ); + } + } + } +} + fn count_cx(candidate: &super::unitary_2q::TwoQubitSynthesisCandidate) -> usize { candidate .operations diff --git a/crates/cqlib-core/src/compile/transform/device_lowering_test.rs b/crates/cqlib-core/src/compile/transform/device_lowering_test.rs index 668db29a..236815aa 100644 --- a/crates/cqlib-core/src/compile/transform/device_lowering_test.rs +++ b/crates/cqlib-core/src/compile/transform/device_lowering_test.rs @@ -975,3 +975,103 @@ fn lowering_wide_sparse_circuit_only_plans_used_qubits() { assert!(result.circuit.operations().len() > circuit.operations().len()); device.validate_circuit(&result.circuit).unwrap(); } + +#[test] +fn universal_single_qubit_native_bases_preserve_symbolic_gates_and_phase() { + use crate::circuit::test_utils::assert_matrix_approx_eq; + use StandardGate::*; + + for basis in [ + vec![U], + vec![RXY], + vec![RZ, X2P], + vec![RZ, X2M], + vec![RZ, Y2P], + vec![RZ, Y2M], + vec![RZ, XY2P], + vec![RZ, XY2M], + ] { + let device = Device::line("single-qubit-basis", 1) + .unwrap() + .with_native_gates(basis.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + let lowerer = DeviceLowerer::new(&device); + // Identity is removed by canonicalization before device lowering. + for &gate in StandardGate::all() + .iter() + .filter(|g| g.num_qubits() == 1 && **g != I) + { + let mut source = Circuit::new(1); + source + .append( + Instruction::Standard(gate), + [Qubit::new(0)], + ["theta", "phi", "lambda"] + .into_iter() + .take(gate.num_params()) + .map(|name| ParameterValue::Param(Parameter::symbol(name))), + None, + ) + .unwrap(); + source.set_global_phase(Parameter::symbol("phase")); + let lowered = lowerer + .transform_resolved(&source, None) + .unwrap_or_else(|e| panic!("{gate:?} -> {basis:?}: {e}")) + .circuit; + device.validate_circuit(&lowered).unwrap(); + if basis == [U] { + assert_eq!(lowered.operations().len(), 1, "{gate:?} must use one U"); + } + assert!(source.symbols().is_subset(lowered.symbols())); + for angle in [0.0, PI / 2.0, -PI, 2.0 * PI, -4.0 * PI, 0.173, -1.239] { + let bindings = Some(HashMap::from([ + ("theta", angle), + ("phi", 0.39 - angle), + ("lambda", -0.71 + 2.0 * angle), + ("phase", -0.37), + ])); + assert_matrix_approx_eq( + &source + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + &lowered + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + 1e-9, + ); + } + } + } +} + +#[test] +fn native_u_lowering_respects_local_capability_override() { + let mut device = Device::line("local-capability", 2) + .unwrap() + .with_native_gates(vec![Instruction::Standard(StandardGate::U)]) + .unwrap(); + device + .add_qubit_properties( + PhysicalQubit::new(1), + QubitProp::new(0.0) + .with_native_instruction(InstructionProp::new( + Instruction::Standard(StandardGate::RZ), + 0.0, + )) + .unwrap(), + ) + .unwrap(); + let lowerer = DeviceLowerer::new(&device); + let mut allowed = Circuit::new(2); + allowed.h(Qubit::new(0)).unwrap(); + device + .validate_circuit(&lowerer.transform_resolved(&allowed, None).unwrap().circuit) + .unwrap(); + let mut blocked = Circuit::new(2); + blocked.h(Qubit::new(1)).unwrap(); + assert!(lowerer.transform_resolved(&blocked, None).is_err()); +} diff --git a/crates/cqlib-core/src/compile/transform/layout/sabre.rs b/crates/cqlib-core/src/compile/transform/layout/sabre.rs index aa7790e1..d5da8aca 100644 --- a/crates/cqlib-core/src/compile/transform/layout/sabre.rs +++ b/crates/cqlib-core/src/compile/transform/layout/sabre.rs @@ -12,6 +12,9 @@ //! SABRE initial-layout adapter. //! +//! Algorithm reference: Gushu Li, Yufei Ding, and Yuan Xie, +//! [Tackling the Qubit Mapping Problem for NISQ-Era Quantum Devices](https://arxiv.org/abs/1809.02573). +//! //! This module owns layout-candidate generation, objective scoring, and //! [`LayoutResult`] construction. The SABRE core remains in //! [`crate::compile::sabre`] and is used here only through crate-internal @@ -418,7 +421,7 @@ pub(crate) struct PreparedSabreParetoSearch { } impl PreparedSabreParetoSearch { - /// Builds the Qiskit-style four-refinement search profile. A supplied + /// Builds the multi-start four-refinement search profile. A supplied /// layout is normalized and kept fixed; generated layouts deliberately do /// not use the dense-interaction refinement shortcut employed by candidate /// zero. diff --git a/crates/cqlib-core/src/compile/transform/resynthesis/resynthesizer_test.rs b/crates/cqlib-core/src/compile/transform/resynthesis/resynthesizer_test.rs index 7b7422ad..b98ea601 100644 --- a/crates/cqlib-core/src/compile/transform/resynthesis/resynthesizer_test.rs +++ b/crates/cqlib-core/src/compile/transform/resynthesis/resynthesizer_test.rs @@ -112,6 +112,71 @@ fn two_qubit_op_count(circuit: &Circuit) -> usize { .count() } +#[test] +fn weyl_boundary_resynthesis_improves_a_valid_interior_block() { + use crate::circuit::test_utils::assert_matrix_approx_eq; + use crate::circuit::{Parameter, circuit_to_matrix}; + + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + let mut circuit = Circuit::new(2); + circuit + .rxx(q0, q1, -2.0 * (std::f64::consts::FRAC_PI_4 - 5e-9)) + .unwrap(); + circuit.ryy(q0, q1, -0.4).unwrap(); + circuit.rzz(q0, q1, 0.06).unwrap(); + for _ in 0..2 { + circuit.cx(q0, q1).unwrap(); + circuit.cx(q0, q1).unwrap(); + } + circuit.set_global_phase(Parameter::from(0.37)); + let expected = circuit_to_matrix(&circuit, None).unwrap(); + let (generic, stats) = + resynthesize_two_qubit_blocks_with_cache_budget(&circuit, cx_config(), 4096).unwrap(); + assert!(generic.changed); + assert!(two_qubit_op_count(&generic.circuit) < two_qubit_op_count(&circuit)); + assert_eq!(stats.kak_failed_hits, 0); + assert_matrix_approx_eq( + &circuit_to_matrix(&generic.circuit, None).unwrap(), + &expected, + 1e-9, + ); + + let device = Device::bidirectional_line("boundary", 2) + .unwrap() + // Cost source and replacement on a device that can execute both. + .with_native_gates(vec![ + Instruction::Standard(StandardGate::U), + Instruction::Standard(StandardGate::CX), + Instruction::Standard(StandardGate::RXX), + Instruction::Standard(StandardGate::RYY), + Instruction::Standard(StandardGate::RZZ), + ]) + .unwrap(); + for placement in [ + DeviceSynthesisPlacement::PreLayoutEnvelope, + DeviceSynthesisPlacement::ExactPhysical, + ] { + let context = build_device_synthesis_context(&device, &circuit, placement).unwrap(); + let (result, stats) = resynthesize_two_qubit_blocks_with_device_cache_budget( + &circuit, + cx_config(), + context, + 4096, + ) + .unwrap(); + assert!(result.changed, "placement={placement:?}, stats={stats:?}"); + assert!(two_qubit_op_count(&result.circuit) < two_qubit_op_count(&circuit)); + assert_eq!(stats.kak_failed_hits, 0); + assert_matrix_approx_eq( + &circuit_to_matrix(&result.circuit, None).unwrap(), + &expected, + 1e-9, + ); + device.validate_circuit(&result.circuit).unwrap(); + } +} + #[test] fn cancels_adjacent_cx_pair() { let q0 = Qubit::new(0); diff --git a/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache.rs b/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache.rs index 7c6987b4..fa933682 100644 --- a/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache.rs +++ b/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache.rs @@ -52,7 +52,7 @@ use super::commutation::OperationView; use super::cost::ResynthesisCost; pub(super) const RESYNTHESIS_SYNTHESIS_CACHE_BUDGET: usize = 4096; -const SYNTHESIS_ALGORITHM_REVISION: u32 = 2; +const SYNTHESIS_ALGORITHM_REVISION: u32 = 3; #[derive(Clone, Debug, PartialEq, Eq)] struct SynthesisCacheNamespace { diff --git a/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache_test.rs b/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache_test.rs index 4712d112..bfdabcdc 100644 --- a/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache_test.rs +++ b/crates/cqlib-core/src/compile/transform/resynthesis/synthesis_cache_test.rs @@ -28,6 +28,20 @@ fn matrix_with(real: f64) -> Array2 { matrix } +#[test] +fn weyl_boundary_kak_cache_stores_a_successful_decomposition() { + let matrix = crate::compile::test_utils::kak_boundary_matrix(); + let mut cache = TwoQubitSynthesisCache::new_native_session(); + let first = cache.kak_decomposition(&matrix).unwrap().unwrap(); + let second = cache.kak_decomposition(&matrix).unwrap().unwrap(); + assert!(Arc::ptr_eq(&first, &second)); + assert_eq!(first.a, std::f64::consts::FRAC_PI_4); + assert!(first.c > 0.0); + assert_eq!(cache.stats().kak_misses, 1); + assert_eq!(cache.stats().kak_hits, 1); + assert_eq!(cache.stats().kak_failed_hits, 0); +} + #[test] fn exact_key_distinguishes_qargs_bits_and_signed_zero() { let q0 = Qubit::new(0); diff --git a/crates/cqlib-core/src/compile/transform/rewrite/rewrite_test.rs b/crates/cqlib-core/src/compile/transform/rewrite/rewrite_test.rs index a4f9a915..c9e5b9e9 100644 --- a/crates/cqlib-core/src/compile/transform/rewrite/rewrite_test.rs +++ b/crates/cqlib-core/src/compile/transform/rewrite/rewrite_test.rs @@ -533,7 +533,7 @@ fn lowering_reaches_target_basis_through_multiple_steps() { } #[test] -fn lowers_ccx_directly_to_multiple_qiskit_basis_sets() { +fn lowers_ccx_directly_to_multiple_native_basis_sets() { let q0 = Qubit::new(0); let q1 = Qubit::new(1); let q2 = Qubit::new(2); @@ -582,7 +582,7 @@ fn lowers_ccx_directly_to_multiple_qiskit_basis_sets() { } #[test] -fn qiskit_rzz_ccx_rule_uses_five_entanglers() { +fn rzz_ccx_rule_uses_five_entanglers() { let q0 = Qubit::new(0); let q1 = Qubit::new(1); let q2 = Qubit::new(2); @@ -612,7 +612,7 @@ fn qiskit_rzz_ccx_rule_uses_five_entanglers() { } #[test] -fn qiskit_cz_ccx_rule_uses_native_x2p_x_rz_cz_template() { +fn cz_ccx_rule_uses_native_x2p_x_rz_cz_template() { let q0 = Qubit::new(0); let q1 = Qubit::new(1); let q2 = Qubit::new(2); diff --git a/crates/cqlib-core/src/compile/transform/target_basis_test.rs b/crates/cqlib-core/src/compile/transform/target_basis_test.rs index bb940e9b..652bcf20 100644 --- a/crates/cqlib-core/src/compile/transform/target_basis_test.rs +++ b/crates/cqlib-core/src/compile/transform/target_basis_test.rs @@ -401,7 +401,7 @@ fn u_fails_for_basis_without_complete_euler_family() { assert_target_lowering_fails_with( &circuit, - &[StandardGate::RZ, StandardGate::X2M], + &[StandardGate::RZ, StandardGate::Z], &["cannot lower", "U"], ); } @@ -986,3 +986,54 @@ fn target_lowering_uses_compact_qcis_decompositions() { } } } + +#[test] +fn symbolic_u_lowers_to_each_single_polarity_half_rotation_basis() { + use StandardGate::*; + for half in [X2P, X2M, Y2P, Y2M] { + let mut source = Circuit::new(1); + source + .u( + Qubit::new(0), + Parameter::symbol("theta"), + Parameter::symbol("phi"), + Parameter::symbol("lambda"), + ) + .unwrap(); + source.set_global_phase((-0.37).into()); + let result = run_target_lowering(&source, &[RZ, half]); + assert_only_target_standard_gates(&result, &[RZ, half]); + assert!( + result.operations().len() <= 5, + "{half:?}: expected a compact Euler path" + ); + for (theta, phi, lambda) in [ + (0.0, 0.0, 0.0), + (0.173, -1.239, 0.71), + ( + std::f64::consts::PI, + -2.0 * std::f64::consts::PI, + 4.0 * std::f64::consts::PI, + ), + ] { + let bindings = Some(std::collections::HashMap::from([ + ("theta", theta), + ("phi", phi), + ("lambda", lambda), + ])); + assert_matrix_approx_eq( + &source + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + &result + .assign_parameters(&bindings) + .unwrap() + .to_matrix(None) + .unwrap(), + 1e-9, + ); + } + } +} diff --git a/crates/cqlib-core/src/compile/workflow_test.rs b/crates/cqlib-core/src/compile/workflow_test.rs index 689dd5b6..26be6681 100644 --- a/crates/cqlib-core/src/compile/workflow_test.rs +++ b/crates/cqlib-core/src/compile/workflow_test.rs @@ -54,6 +54,61 @@ fn compile_config(mode: CompileMode) -> CompileConfig { } } +#[test] +fn weyl_boundary_workflow_preserves_phase_for_logical_basis_and_device_targets() { + use crate::circuit::{circuit_to_matrix, test_utils::assert_matrix_approx_eq}; + use crate::compile::test_utils::kak_boundary_matrix; + let mut circuit = Circuit::new(2); + circuit + .unitary( + UnitaryGate::new("boundary", 2, 0) + .with_matrix(kak_boundary_matrix()) + .unwrap(), + vec![Qubit::new(1), Qubit::new(0)], + ) + .unwrap(); + circuit.set_global_phase(Parameter::from(-0.41)); + let expected = circuit_to_matrix(&circuit, None).unwrap(); + let native = vec![ + Instruction::Standard(StandardGate::U), + Instruction::Standard(StandardGate::CX), + ]; + let device = Device::bidirectional_line("boundary", 2) + .unwrap() + .with_native_gates(native.clone()) + .unwrap(); + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + for target in [ + CompileTarget::Logical, + CompileTarget::Basis(native.clone()), + CompileTarget::Device(DeviceCompileTarget { + device: device.clone(), + initial_layout: Some(Layout::from_pairs(&[(0, 0), (1, 1)], 2).unwrap()), + seed: Some(41), + }), + ] { + let is_device = matches!(&target, CompileTarget::Device(_)); + let result = compile( + &circuit, + CompileConfig { + target, + ..compile_config(mode) + }, + ) + .unwrap(); + assert!(result.step_changed("decompose.unitary")); + assert_matrix_approx_eq( + &circuit_to_matrix(&result.circuit, None).unwrap(), + &expected, + 1e-9, + ); + if is_device { + device.validate_circuit(&result.circuit).unwrap(); + } + } + } +} + #[test] fn xy_basis_compiles_generic_u_to_three_rotations_in_both_modes() { let mut circuit = Circuit::new(1); @@ -1365,6 +1420,81 @@ fn workflow_expands_circuit_gate_definitions_before_optimization() { assert!(!contains_high_level_gate(&result.circuit)); } +#[test] +fn workflow_preserves_qasm_gate_signatures_in_both_modes() { + let declarations = r#" + gate reordered(phi, theta) a, b { + rx(theta) a; + rz(phi) b; + cx a, b; + } + gate declared(unused, phi, theta) a, b { + reordered(phi, theta) a, b; + } + "#; + let mut expected = Circuit::new(2); + expected.rx(Qubit::new(1), -0.2).unwrap(); + expected.rz(Qubit::new(0), 0.7).unwrap(); + expected.cx(Qubit::new(1), Qubit::new(0)).unwrap(); + let expected_matrix = crate::circuit::circuit_to_matrix(&expected, None).unwrap(); + let basis = vec![ + Instruction::Standard(StandardGate::RX), + Instruction::Standard(StandardGate::RY), + Instruction::Standard(StandardGate::CZ), + ]; + let device = Device::bidirectional_line("declared-signatures", 2) + .unwrap() + .with_native_gates(basis.clone()) + .unwrap(); + + for call in ["reordered(0.7, -0.2)", "declared(11.0, 0.7, -0.2)"] { + let qasm2 = format!( + "OPENQASM 2.0; include \"qelib1.inc\"; {declarations} qreg q[2]; {call} q[1], q[0];" + ); + let qasm3 = format!( + "OPENQASM 3.0; include \"stdgates.inc\"; {declarations} qubit[2] q; {call} q[1], q[0];" + ); + for circuit in [ + crate::ir::qasm2_loads(&qasm2).unwrap(), + crate::ir::qasm3_loads(&qasm3).unwrap(), + ] { + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + for target in [ + CompileTarget::Logical, + CompileTarget::Basis(basis.clone()), + CompileTarget::Device(DeviceCompileTarget { + device: device.clone(), + initial_layout: Some(Layout::from_pairs(&[(0, 0), (1, 1)], 2).unwrap()), + seed: Some(47), + }), + ] { + let device_target = matches!(target, CompileTarget::Device(_)); + let result = compile( + &circuit, + CompileConfig { + mode, + target, + resource_policy: ResourcePolicy::default(), + }, + ) + .unwrap(); + + assert!(result.step_changed("decompose.definitions")); + assert!(!contains_high_level_gate(&result.circuit)); + crate::circuit::test_utils::assert_matrix_approx_eq( + &crate::circuit::circuit_to_matrix(&result.circuit, None).unwrap(), + &expected_matrix, + 1e-9, + ); + if device_target { + device.validate_circuit(&result.circuit).unwrap(); + } + } + } + } + } +} + #[test] fn definition_expansion_invalidates_analysis_before_unitary_decomposition() { let q0 = Qubit::new(0); @@ -3723,3 +3853,195 @@ fn shared_device_workflow_supports_concurrent_mixed_runs() { handle.join().unwrap(); } } + +#[test] +fn heterogeneous_native_entanglers_remain_executable_without_fsim_detours() { + use crate::device::QubitProp; + use StandardGate::*; + + for (basis, singles, edges) in [ + ( + vec![U, CZ], + [(0.001, 84.0), (0.006, 45.0)], + [(0.019, 59.0), (0.016, 293.0)], + ), + ( + vec![RY, RZ, CX], + [(0.001, 10.0), (0.009, 80.0)], + [(0.01, 50.0), (0.03, 200.0)], + ), + ] { + let mut device = Device::bidirectional_line("heterogeneous-native-entangler", 2) + .unwrap() + .with_native_gates(basis.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + for (q, (error, duration)) in singles.into_iter().enumerate() { + let mut prop = QubitProp::new(0.0); + for &gate in basis.iter().filter(|gate| gate.num_qubits() == 1) { + prop = prop + .with_native_instruction( + InstructionProp::new(Instruction::Standard(gate), error) + .with_length(duration), + ) + .unwrap(); + } + device + .add_qubit_properties(PhysicalQubit::new(q as u32), prop) + .unwrap(); + } + let entangler = *basis.last().unwrap(); + for ((a, b), (error, duration)) in [(0, 1), (1, 0)].into_iter().zip(edges) { + device + .add_edge_properties( + PhysicalQubit::new(a), + PhysicalQubit::new(b), + EdgeProp::new() + .with_native_instruction( + InstructionProp::new(Instruction::Standard(entangler), error) + .with_length(duration), + ) + .unwrap(), + ) + .unwrap(); + } + for (a, b) in [(0, 1), (1, 0)] { + let mut source = Circuit::new(2); + source + .append( + Instruction::Standard(entangler), + [Qubit::new(a), Qubit::new(b)], + [], + None, + ) + .unwrap(); + source.set_global_phase((-0.37).into()); + device.validate_circuit(&source).unwrap(); + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + let result = compile( + &source, + CompileConfig { + target: CompileTarget::Device(DeviceCompileTarget { + device: device.clone(), + initial_layout: Some(Layout::from_pairs(&[(0, 0), (1, 1)], 2).unwrap()), + seed: Some(7), + }), + ..compile_config(mode) + }, + ) + .unwrap_or_else(|e| panic!("{basis:?}/{a}->{b}/{mode:?}: {e}")); + device.validate_circuit(&result.circuit).unwrap(); + assert_eq!(result.circuit.operations().len(), 1); + crate::circuit::test_utils::assert_matrix_approx_eq( + &source.to_matrix(Some(&[0, 1])).unwrap(), + &result.circuit.to_matrix(Some(&[0, 1])).unwrap(), + 1e-9, + ); + } + } + } +} + +#[test] +fn universal_native_bases_route_on_directed_chain_with_exact_layout_isometry() { + use StandardGate::*; + + for native in [ + vec![U, CX], + vec![U, CZ], + vec![RY, RZ, CX], + vec![RY, RZ, CZ], + vec![U, H, CX], + vec![RXY, CX], + vec![RXY, CZ], + vec![RZ, X2P, CZ], + vec![RZ, X2M, CX], + vec![RZ, Y2P, CX], + vec![RZ, Y2M, CZ], + vec![RZ, XY2P, CZ], + vec![RZ, XY2M, CX], + ] { + let device = Device::from_edges("native-universality", 4, &[(0, 1), (1, 2), (2, 3)]) + .unwrap() + .with_native_gates(native.iter().copied().map(Instruction::Standard).collect()) + .unwrap(); + for (label, pairs) in [ + ("H", vec![]), + ("forward CX", vec![(0, 1)]), + ("both directions", vec![(0, 1), (1, 0)]), + ("triangle", vec![(0, 1), (1, 2), (2, 0)]), + ("mixed", vec![(0, 2), (2, 1), (1, 0)]), + ] { + let n = if matches!(label, "triangle" | "mixed") { + 3 + } else { + 2 + }; + let mut source = Circuit::new(n); + if pairs.is_empty() { + source.h(Qubit::new(0)).unwrap(); + } + for (a, b) in pairs { + source.cx(Qubit::new(a), Qubit::new(b)).unwrap(); + } + if label == "mixed" { + source.u(Qubit::new(0), 0.173, -1.239, 0.71).unwrap(); + source.crz(Qubit::new(0), Qubit::new(2), -0.43).unwrap(); + source + .fsim(Qubit::new(2), Qubit::new(1), 0.31, -0.27) + .unwrap(); + } + source.set_global_phase((-0.37).into()); + let expected = source.to_matrix(None).unwrap(); + for mode in [CompileMode::Normal, CompileMode::Enhanced] { + let result = compile( + &source, + CompileConfig { + target: CompileTarget::Device(DeviceCompileTarget { + device: device.clone(), + initial_layout: None, + seed: Some(7), + }), + ..compile_config(mode) + }, + ) + .unwrap_or_else(|e| panic!("{native:?}/{label}/{mode:?}: {e}")); + device.validate_circuit(&result.circuit).unwrap(); + let metadata = result.device_metadata.unwrap(); + let order: Vec<_> = result.circuit.qubits().iter().map(|q| q.index()).collect(); + let actual = result.circuit.to_matrix(Some(&order)).unwrap(); + let encode = |state: usize, layout: &Layout| -> usize { + (0..n) + .map(|q| { + let physical = layout + .get_physical(LogicalQubit::new(q as u32)) + .unwrap() + .id() as usize; + ((state >> q) & 1) << order.iter().position(|&p| p == physical).unwrap() + }) + .sum() + }; + // Every computational input and every physical output, + // including outputs with a nonzero unused physical qubit. + for column in 0..1 << n { + let logical_rows: HashMap<_, _> = (0..1 << n) + .map(|row| (encode(row, &metadata.final_layout), row)) + .collect(); + for row in 0..actual.nrows() { + let value = logical_rows + .get(&row) + .map_or(Complex64::new(0.0, 0.0), |&logical| { + expected[[logical, column]] + }); + let error = (value + - actual[[row, encode(column, &metadata.initial_layout)]]) + .norm(); + assert!( + error < 1e-8, + "{native:?}/{label}/{mode:?}: matrix error {error}" + ); + } + } + } + } + } +} diff --git a/crates/cqlib-core/src/device/device_impl.rs b/crates/cqlib-core/src/device/device_impl.rs index 49987693..68ffa95a 100644 --- a/crates/cqlib-core/src/device/device_impl.rs +++ b/crates/cqlib-core/src/device/device_impl.rs @@ -472,10 +472,17 @@ impl Device { /// /// The device contains every supplied physical qubit, all of which are /// online. Couplings follow the supplied order: `qubits[i] -> qubits[i + 1]`. + /// + /// # Errors + /// + /// Returns [`DeviceError::EmptyDevice`] if `physical_qubits` is empty. pub fn line_from_qubits( name: impl Into, physical_qubits: Vec, ) -> Result { + if physical_qubits.is_empty() { + return Err(DeviceError::EmptyDevice); + } let qubits = physical_qubits.iter().copied().collect::>(); let topology = Topology::line(physical_qubits).map_err(DeviceError::InvalidTopology)?; Self::new(name, qubits, topology) @@ -569,6 +576,9 @@ impl Device { num_qubits: u32, edges: &[(u32, u32)], ) -> Result { + if num_qubits == 0 { + return Err(DeviceError::EmptyDevice); + } let physical_qubits = (0..num_qubits).map(PhysicalQubit::new).collect::>(); let qubits = physical_qubits.iter().copied().collect::>(); let coupling_map = edges diff --git a/crates/cqlib-core/src/device/device_test.rs b/crates/cqlib-core/src/device/device_test.rs index 463f611e..3d6681c1 100644 --- a/crates/cqlib-core/src/device/device_test.rs +++ b/crates/cqlib-core/src/device/device_test.rs @@ -359,6 +359,42 @@ fn grid_device_uses_row_major_bidirectional_nearest_neighbors() { ); } +#[test] +fn device_factories_reject_zero_qubits() { + assert_eq!( + Device::line("bad", 0).unwrap_err(), + DeviceError::EmptyDevice + ); + assert_eq!( + Device::line_from_qubits("bad", vec![]).unwrap_err(), + DeviceError::EmptyDevice + ); + assert_eq!( + Device::bidirectional_line("bad", 0).unwrap_err(), + DeviceError::EmptyDevice + ); + assert_eq!( + Device::ring("bad", 0).unwrap_err(), + DeviceError::EmptyDevice + ); + assert_eq!( + Device::star("bad", 0, 0).unwrap_err(), + DeviceError::EmptyDevice + ); + assert_eq!( + Device::grid("bad", 0, 3).unwrap_err(), + DeviceError::EmptyDevice + ); + assert_eq!( + Device::grid("bad", 3, 0).unwrap_err(), + DeviceError::EmptyDevice + ); + assert_eq!( + Device::from_edges("bad", 0, &[]).unwrap_err(), + DeviceError::EmptyDevice + ); +} + #[test] fn from_edges_creates_explicit_directed_couplings() { let device = Device::from_edges("custom", 3, &[(0, 2), (2, 1)]).unwrap(); diff --git a/crates/cqlib-core/src/device/error.rs b/crates/cqlib-core/src/device/error.rs index 5491a48b..675aafb1 100644 --- a/crates/cqlib-core/src/device/error.rs +++ b/crates/cqlib-core/src/device/error.rs @@ -22,6 +22,8 @@ use thiserror::Error; #[derive(Error, Debug, Clone, PartialEq, Eq)] pub enum DeviceError { + /// The device must contain at least one physical qubit. + EmptyDevice, InvalidOnlineQubit(PhysicalQubit), QubitNotInDevice(PhysicalQubit), QubitNotInTopology(PhysicalQubit), @@ -153,6 +155,9 @@ impl std::error::Error for DeviceValidationError {} impl fmt::Display for DeviceError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::EmptyDevice => { + write!(f, "Device must contain at least one physical qubit") + } Self::InvalidOnlineQubit(q) => { write!( f, diff --git a/crates/cqlib-core/src/device/noise.rs b/crates/cqlib-core/src/device/noise.rs index 9bcd9528..7b861e45 100644 --- a/crates/cqlib-core/src/device/noise.rs +++ b/crates/cqlib-core/src/device/noise.rs @@ -164,7 +164,7 @@ impl SingleQubitNoise { ] } Self::Pauli { px, py, pz } => { - let pi = (1.0 - px - py - pz).sqrt(); + let pi = (1.0 - (px + py + pz)).sqrt(); vec![ Pauli::I.to_matrix() * pi, Pauli::X.to_matrix() * px.sqrt(), @@ -558,4 +558,36 @@ mod tests { result => panic!("unexpected result: {result:?}"), } } + + #[test] + fn pauli_probability_boundary_has_complete_finite_kraus_operators() { + let noise = SingleQubitNoise::Pauli { + px: 0.3, + py: 0.6, + pz: 0.1, + }; + assert!(noise.is_valid()); + let ops = noise.to_kraus(); + let mut completeness = ndarray::Array2::::zeros((2, 2)); + for op in &ops { + assert!(op.iter().all(|v| v.re.is_finite() && v.im.is_finite())); + completeness += &op.t().mapv(|v| v.conj()).dot(op); + } + for i in 0..2 { + for j in 0..2 { + assert!( + (completeness[[i, j]] - Complex64::from(if i == j { 1.0 } else { 0.0 })).norm() + < 1e-12 + ); + } + } + assert!( + !SingleQubitNoise::Pauli { + px: 0.4, + py: 0.6, + pz: 0.1 + } + .is_valid() + ); + } } diff --git a/crates/cqlib-core/src/error_mitigation/error_mitigation_test.rs b/crates/cqlib-core/src/error_mitigation/error_mitigation_test.rs index 55114d3a..34fd8823 100644 --- a/crates/cqlib-core/src/error_mitigation/error_mitigation_test.rs +++ b/crates/cqlib-core/src/error_mitigation/error_mitigation_test.rs @@ -270,14 +270,20 @@ fn test_error_mitigation_vd_run_then_get_mitigated() { }, &|circuit, hamiltonian_arg, shots| { let ops = circuit.operations(); - assert_eq!(ops.len(), 1); + assert_eq!(ops.len(), 2); assert!(matches!( ops[0].instruction, - Instruction::Standard(StandardGate::SWAP) + Instruction::Standard(StandardGate::H) )); + assert!(matches!(ops[1].instruction, Instruction::McGate(_))); - if let Some(expanded_hamiltonian) = hamiltonian_arg { - assert_eq!(expanded_hamiltonian.num_qubits, 2); + let expanded_hamiltonian = + hamiltonian_arg.expect("numerator and denominator both provide a Hamiltonian"); + assert_eq!(expanded_hamiltonian.num_qubits, 3); + let (term, _coeff) = &expanded_hamiltonian.terms[0]; + assert_eq!((term.x[2], term.z[2]), (true, false)); + + if (term.x[0], term.z[0]) != (false, false) { assert_eq!(shots, Some(3)); (1.5, 0.25) } else { diff --git a/crates/cqlib-core/src/error_mitigation/unified.rs b/crates/cqlib-core/src/error_mitigation/unified.rs index f6ba05a3..593a4541 100644 --- a/crates/cqlib-core/src/error_mitigation/unified.rs +++ b/crates/cqlib-core/src/error_mitigation/unified.rs @@ -221,7 +221,10 @@ struct VirtualDistillationRunRecord { /// /// // A portal to real quantum device or classical simulation backend that calculates and its variance /// let estimator = |_circuit: &Circuit, hamiltonian: Option<&Hamiltonian>, _shots: Option| { -/// if hamiltonian.is_some() { +/// // Both the numerator and the denominator carry a Hamiltonian: the +/// // numerator additionally acts on the first copy (qubit 0 here). +/// let term = &hamiltonian.unwrap().terms[0].0; +/// if term.x[0] || term.z[0] { /// (1.5, 0.25) /// } else { /// (2.0, 1.0) @@ -307,7 +310,10 @@ impl ErrorMitigation { /// /// // A portal to real quantum device or classical simulation backend that calculates and its variance /// let estimator = |_circuit: &Circuit, hamiltonian: Option<&Hamiltonian>, _shots: Option| { - /// if hamiltonian.is_some() { + /// // Both the numerator and the denominator carry a Hamiltonian: the + /// // numerator additionally acts on the first copy (qubit 0 here). + /// let term = &hamiltonian.unwrap().terms[0].0; + /// if term.x[0] || term.z[0] { /// (1.0, 0.1) /// } else { /// (2.0, 0.2) @@ -526,16 +532,8 @@ impl ErrorMitigation { }); } - let copy_swap_circuit = vd.build_copy_swap_circuit()?; - let extra_qubits = copy_swap_circuit.width() - hamiltonian.num_qubits; - let expanded_hamiltonian = - VirtualDistillation::expand_hamiltonian(hamiltonian, extra_qubits)?; - let numerator = estimator( - ©_swap_circuit, - Some(&expanded_hamiltonian), - Some(shots_numerator), - ); - let denominator = estimator(©_swap_circuit, None, Some(shots_denominator)); + let numerator = vd.run_numerator_circuit(hamiltonian, shots_numerator, estimator)?; + let denominator = vd.run_denominator_circuit(shots_denominator, estimator)?; Ok(VirtualDistillationRunRecord { numerator, diff --git a/crates/cqlib-core/src/error_mitigation/virtual_distillation.rs b/crates/cqlib-core/src/error_mitigation/virtual_distillation.rs index 387c42b4..587e8db7 100644 --- a/crates/cqlib-core/src/error_mitigation/virtual_distillation.rs +++ b/crates/cqlib-core/src/error_mitigation/virtual_distillation.rs @@ -12,7 +12,9 @@ use std::collections::HashMap; -use crate::circuit::{Circuit, CircuitError, CircuitParam, ParameterValue, Qubit}; +use num_complex::Complex64; + +use crate::circuit::{Circuit, CircuitError, CircuitParam, ParameterValue, Qubit, StandardGate}; use crate::error_mitigation::ErrorMitigationError; use crate::error_mitigation::Estimator; use crate::qis::{Hamiltonian, Pauli, PauliString}; @@ -65,53 +67,76 @@ impl VirtualDistillation { Ok(()) } - /// Builds a copy-swap circuit from the configured base circuit. + /// Builds the virtual distillation circuit from the configured base circuit. /// /// The returned circuit contains: /// - `copies` disjoint copies of the base circuit preparation, - /// - pairwise SWAP operations between the first copy and every additional copy. + /// - one ancillary qubit (the last qubit, index `copies * base_width`), + /// prepared in `|+>` by a Hadamard gate, + /// - a derangement of the copies implemented as a ladder of swap gates + /// between adjacent copies, each controlled by the ancillary qubit + /// (CSWAP). + /// + /// This is the Hadamard-test circuit of the virtual distillation protocol: + /// measuring `X` on the ancillary qubit (together with an observable on the + /// first copy) yields `Tr(O rho^M)` / `Tr(rho^M)`. Applying uncontrolled + /// swaps instead would leave the permutation-symmetric state `rho^M` + /// invariant and measure nothing related to the distilled moments. pub fn build_copy_swap_circuit(&self) -> Result { let base_circuit = self.circuit.decompose()?; let base_width = base_circuit.width(); - let mut copy_swap_circuit = Circuit::new(self.copies * base_width); + let ancilla = Qubit::new((self.copies * base_width) as u32); + let mut copy_swap_circuit = Circuit::new(self.copies * base_width + 1); for copy_index in 0..self.copies { let copy_offset = copy_index * base_width; Self::append_circuit_with_offset(&mut copy_swap_circuit, &base_circuit, copy_offset)?; } - for other_copy in 1..self.copies { - let first_copy_offset = 0; - let other_copy_offset = other_copy * base_width; + copy_swap_circuit.h(ancilla)?; + + for lower_copy in 0..(self.copies - 1) { + let lower_offset = lower_copy * base_width; + let upper_offset = (lower_copy + 1) * base_width; for qubit_index in 0..base_width { - let left = Qubit::new((first_copy_offset + qubit_index) as u32); - let right = Qubit::new((other_copy_offset + qubit_index) as u32); - copy_swap_circuit.swap(left, right)?; + let lower = Qubit::new((lower_offset + qubit_index) as u32); + let upper = Qubit::new((upper_offset + qubit_index) as u32); + copy_swap_circuit.multi_control( + StandardGate::SWAP, + [ancilla], + [lower, upper], + [], + )?; } } Ok(copy_swap_circuit) } - /// Expands a Hamiltonian to the full copy-swap circuit width. + /// Expands a Hamiltonian to the numerator observable on the full virtual + /// distillation circuit width. /// - /// Virtual distillation evaluates the numerator on a wider copy-swap circuit, - /// so the estimator needs a Hamiltonian of matching width. This helper keeps - /// the original Pauli operators on their current qubit indices and appends - /// `n` `Z`s on higher-index qubits. + /// The numerator of virtual distillation estimates `Tr(O rho^M)`, measured + /// as the expectation value of `X` on the ancillary qubit tensored with the + /// observable on the first copy and identities on the remaining copies. + /// This helper keeps the original Pauli operators on their current qubit + /// indices, pads identities on the additional copies, and appends an `X` + /// on the ancillary qubit (the last qubit). pub(crate) fn expand_hamiltonian( hamiltonian: &Hamiltonian, - n: usize, + copies: usize, ) -> Result { + let width = hamiltonian.num_qubits * copies + 1; + let ancilla = width - 1; if hamiltonian.terms.is_empty() { - return Ok(Hamiltonian::new(hamiltonian.num_qubits + n)); + return Ok(Hamiltonian::new(width)); } let expanded_terms = hamiltonian .terms .iter() .map(|(term, coeff)| { - let mut expanded_term = PauliString::new(hamiltonian.num_qubits + n); + let mut expanded_term = PauliString::new(width); expanded_term.phase = term.phase; for qubit in 0..hamiltonian.num_qubits { @@ -124,9 +149,7 @@ impl VirtualDistillation { expanded_term.set_pauli(qubit, pauli); } - for qubit in hamiltonian.num_qubits..(hamiltonian.num_qubits + n) { - expanded_term.set_pauli(qubit, Pauli::Z); - } + expanded_term.set_pauli(ancilla, Pauli::X); (expanded_term, *coeff) }) @@ -135,35 +158,58 @@ impl VirtualDistillation { Ok(Hamiltonian::from_list(expanded_terms)?) } + /// Returns the denominator observable of virtual distillation. + /// + /// The denominator estimates `Tr(rho^M)`, measured as the expectation + /// value of `X` on the ancillary qubit (the last qubit) with identities + /// everywhere else. + fn denominator_hamiltonian(&self) -> Result { + let width = self.copies * self.circuit.width() + 1; + let mut term = PauliString::new(width); + term.set_pauli(width - 1, Pauli::X); + Ok(Hamiltonian::from_list(vec![( + term, + Complex64::new(1.0, 0.0), + )])?) + } + /// Runs the denominator circuit and returns the estimated mean and variance. /// /// - `shots`: the number of shots to run the circuit. - /// - `estimator`: an estimator that evaluates the copy-swap circuit, with no - /// Hamiltonian (`None`) and the provided shot count. + /// - `estimator`: an estimator that evaluates the virtual distillation + /// circuit with the denominator observable (`X` on the ancillary qubit, + /// identities elsewhere) and the provided shot count. /// /// # Returns /// - /// - `(mu, var)`: the estimated mean and variance of the denominator circuit. + /// - `(mu, var)`: the estimated mean and variance of `Tr(rho^M)`. pub fn run_denominator_circuit( &self, shots: usize, estimator: &Estimator<'_>, - ) -> Result<(f64, f64), CircuitError> { + ) -> Result<(f64, f64), ErrorMitigationError> { let denominator_circuit = self.build_copy_swap_circuit()?; + let denominator_hamiltonian = self.denominator_hamiltonian()?; - Ok(estimator(&denominator_circuit, None, Some(shots))) + Ok(estimator( + &denominator_circuit, + Some(&denominator_hamiltonian), + Some(shots), + )) } /// Runs the numerator circuit and returns the estimated mean and variance. /// - /// - `hamiltonian`: the Hamiltonian to estimate on the copy-swap circuit. + /// - `hamiltonian`: the Hamiltonian to estimate on the virtual distillation + /// circuit. It is expanded to the full circuit width with `X` on the + /// ancillary qubit (see [`Self::expand_hamiltonian`]). /// - `shots`: the number of shots to run the circuit. - /// - `estimator`: an estimator that evaluates the copy-swap circuit, the given - /// expanded Hamiltonian, and the provided shot count. + /// - `estimator`: an estimator that evaluates the virtual distillation + /// circuit, the given expanded Hamiltonian, and the provided shot count. /// /// # Returns /// - /// - `(mu, var)`: the estimated mean and variance of the numerator circuit. + /// - `(mu, var)`: the estimated mean and variance of `Tr(H rho^M)`. pub fn run_numerator_circuit( &self, hamiltonian: &Hamiltonian, @@ -171,8 +217,7 @@ impl VirtualDistillation { estimator: &Estimator<'_>, ) -> Result<(f64, f64), ErrorMitigationError> { let numerator_circuit = self.build_copy_swap_circuit()?; - let extra_qubits = (self.copies - 1) * hamiltonian.num_qubits; - let expanded_hamiltonian = Self::expand_hamiltonian(hamiltonian, extra_qubits)?; + let expanded_hamiltonian = Self::expand_hamiltonian(hamiltonian, self.copies)?; if expanded_hamiltonian.num_qubits != numerator_circuit.width() { return Err(CircuitError::QubitCountMismatch { expected: numerator_circuit.width(), diff --git a/crates/cqlib-core/src/error_mitigation/virtual_distillation_test.rs b/crates/cqlib-core/src/error_mitigation/virtual_distillation_test.rs index e9d9cc38..530ab84c 100644 --- a/crates/cqlib-core/src/error_mitigation/virtual_distillation_test.rs +++ b/crates/cqlib-core/src/error_mitigation/virtual_distillation_test.rs @@ -11,12 +11,12 @@ // that they have been altered from the originals. use super::VirtualDistillation; -use crate::circuit::Qubit; use crate::circuit::circuit_impl::Circuit; use crate::circuit::gate::Instruction; use crate::circuit::gate::standard_gate::StandardGate; +use crate::circuit::{CircuitParam, Qubit}; use crate::error_mitigation::ErrorMitigationError; -use crate::qis::{Hamiltonian, Pauli, PauliString}; +use crate::qis::{DensityMatrix, Hamiltonian, Pauli, PauliString}; use num_complex::Complex64; fn single_qubit_z_hamiltonian() -> Hamiltonian { @@ -33,6 +33,88 @@ fn single_qubit_x_hamiltonian() -> Hamiltonian { .expect("single-qubit X Hamiltonian should be valid") } +/// Exact density-matrix estimator used by the numerical tests. +fn exact_estimator( + circuit: &Circuit, + hamiltonian: Option<&Hamiltonian>, + _shots: Option, +) -> (f64, f64) { + let mut state = DensityMatrix::new(circuit.num_qubits()); + state.apply_circuit(circuit).unwrap(); + let hamiltonian = hamiltonian.expect("numerator and denominator both provide a Hamiltonian"); + (state.expectation(hamiltonian).unwrap(), 0.0) +} + +/// Estimator that prepares `copies` depolarized states and then applies the +/// controlled derangement. It simulates the preparation ops, injects an +/// identical depolarizing channel with strength `p` on every copy register +/// (all qubits except the ancillary), and finally applies the Hadamard on the +/// ancillary and the controlled swap ladder. Depolarizing the disjoint copy +/// registers after the whole preparation phase is equivalent to depolarizing +/// each copy right after its own preparation. +fn depolarizing_estimator( + p: f64, +) -> impl Fn(&Circuit, Option<&Hamiltonian>, Option) -> (f64, f64) { + move |circuit, hamiltonian, _shots| { + let num_qubits = circuit.num_qubits(); + let mut state = DensityMatrix::new(num_qubits); + + let keep = (1.0 - p).sqrt(); + let flip = (p / 3.0).sqrt(); + let c = |re: f64, im: f64| Complex64::new(re, im); + let k0 = vec![c(keep, 0.0), c(0.0, 0.0), c(0.0, 0.0), c(keep, 0.0)]; + let k1 = vec![c(0.0, 0.0), c(flip, 0.0), c(flip, 0.0), c(0.0, 0.0)]; + let k2 = vec![c(0.0, 0.0), c(0.0, -flip), c(0.0, flip), c(0.0, 0.0)]; + let k3 = vec![c(flip, 0.0), c(0.0, 0.0), c(0.0, 0.0), c(-flip, 0.0)]; + + // The Hadamard on the ancillary qubit separates the preparation phase + // from the derangement phase. + let derangement_start = circuit + .operations() + .iter() + .position(|op| matches!(op.instruction, Instruction::Standard(StandardGate::H))) + .expect("virtual distillation circuit must contain the ancillary Hadamard"); + + let mut noise_injected = false; + for (index, op) in circuit.operations().iter().enumerate() { + if !noise_injected && index == derangement_start { + for qubit in 0..(num_qubits - 1) { + state + .apply_kraus(&[k0.clone(), k1.clone(), k2.clone(), k3.clone()], &[qubit]) + .unwrap(); + } + noise_injected = true; + } + + let qubit_indices: Vec = op.qubits.iter().map(|q| q.id() as usize).collect(); + let params: Vec = op + .params + .iter() + .map(|param| match param { + CircuitParam::Fixed(value) => *value, + CircuitParam::Index(_) => panic!("test circuits use fixed parameters only"), + }) + .collect(); + match &op.instruction { + Instruction::Standard(gate) => { + state + .apply_standard_gate(*gate, &qubit_indices, ¶ms) + .unwrap(); + } + Instruction::McGate(mc_gate) => { + let matrix = mc_gate.matrix(¶ms).unwrap(); + state.apply_unitary_gate(&qubit_indices, &matrix).unwrap(); + } + instruction => panic!("unexpected instruction in VD circuit: {instruction:?}"), + } + } + + let hamiltonian = + hamiltonian.expect("numerator and denominator both provide a Hamiltonian"); + (state.expectation(hamiltonian).unwrap(), 0.0) + } +} + #[test] fn test_vd_new_accepts_valid_input() { let circuit = Circuit::new(1); @@ -72,8 +154,10 @@ fn test_build_copy_swap_circuit_for_two_single_qubit_copies() { let copy_swap = vd.build_copy_swap_circuit().unwrap(); let ops = copy_swap.operations(); - assert_eq!(copy_swap.width(), 2); - assert_eq!(ops.len(), 3); + // Two base-circuit copies, a Hadamard on the ancillary qubit, and one + // ancillary-controlled SWAP (CSWAP) between the copies. + assert_eq!(copy_swap.width(), 3); + assert_eq!(ops.len(), 4); assert!(matches!( ops[0].instruction, @@ -89,62 +173,114 @@ fn test_build_copy_swap_circuit_for_two_single_qubit_copies() { assert!(matches!( ops[2].instruction, - Instruction::Standard(StandardGate::SWAP) + Instruction::Standard(StandardGate::H) )); - assert_eq!(ops[2].qubits.as_slice(), &[Qubit::new(0), Qubit::new(1)]); + assert_eq!(ops[2].qubits.as_slice(), &[Qubit::new(2)]); + + match &ops[3].instruction { + Instruction::McGate(mc_gate) => { + assert_eq!(mc_gate.num_ctrl_qubits(), 1); + assert_eq!(*mc_gate.base_gate(), StandardGate::SWAP); + } + instruction => panic!("expected a controlled SWAP, got {instruction:?}"), + } + assert_eq!( + ops[3].qubits.as_slice(), + &[Qubit::new(2), Qubit::new(0), Qubit::new(1)] + ); } #[test] -fn test_build_copy_swap_circuit_adds_pairwise_swaps_for_multiple_copies() { +fn test_build_copy_swap_circuit_adds_controlled_swap_ladder_for_multiple_copies() { let vd = VirtualDistillation::new(Circuit::new(1), 3).unwrap(); let copy_swap = vd.build_copy_swap_circuit().unwrap(); let ops = copy_swap.operations(); - assert_eq!(copy_swap.width(), 3); - assert_eq!(ops.len(), 2); + assert_eq!(copy_swap.width(), 4); + assert_eq!(ops.len(), 3); - let swap_count = ops + assert!(matches!( + ops[0].instruction, + Instruction::Standard(StandardGate::H) + )); + assert_eq!(ops[0].qubits.as_slice(), &[Qubit::new(3)]); + + let cswap_qubits: Vec<_> = ops[1..] .iter() - .filter(|op| matches!(op.instruction, Instruction::Standard(StandardGate::SWAP))) - .count(); - assert_eq!(swap_count, 2); + .map(|op| { + match &op.instruction { + Instruction::McGate(mc_gate) => { + assert_eq!(mc_gate.num_ctrl_qubits(), 1); + assert_eq!(*mc_gate.base_gate(), StandardGate::SWAP); + } + instruction => panic!("expected a controlled SWAP, got {instruction:?}"), + } + op.qubits.as_slice().to_vec() + }) + .collect(); + // Swap ladder between adjacent copies, all controlled by the ancillary. + assert_eq!( + cswap_qubits, + vec![ + vec![Qubit::new(3), Qubit::new(0), Qubit::new(1)], + vec![Qubit::new(3), Qubit::new(1), Qubit::new(2)], + ] + ); } #[test] -fn test_expand_hamiltonian_appends_z_on_higher_indices() { +fn test_expand_hamiltonian_places_x_on_ancilla_and_identity_on_extra_copies() { let hamiltonian = single_qubit_x_hamiltonian(); - let expanded = VirtualDistillation::expand_hamiltonian(&hamiltonian, 2).unwrap(); + let expanded = VirtualDistillation::expand_hamiltonian(&hamiltonian, 3).unwrap(); - assert_eq!(expanded.num_qubits, 3); + assert_eq!(expanded.num_qubits, 4); assert_eq!(expanded.terms.len(), 1); let (term, coeff) = &expanded.terms[0]; assert_eq!(*coeff, Complex64::new(1.0, 0.0)); - assert_eq!(term.num_qubits, 3); + assert_eq!(term.num_qubits, 4); assert_eq!(term.phase, crate::qis::Phase::Plus); + // Observable on the first copy, identities on the extra copies, X on the + // ancillary qubit. assert_eq!((term.x[0], term.z[0]), (true, false)); - assert_eq!((term.x[1], term.z[1]), (false, true)); - assert_eq!((term.x[2], term.z[2]), (false, true)); + assert_eq!((term.x[1], term.z[1]), (false, false)); + assert_eq!((term.x[2], term.z[2]), (false, false)); + assert_eq!((term.x[3], term.z[3]), (true, false)); } #[test] -fn test_run_denominator_circuit_runs_copy_swap_circuit() { +fn test_run_denominator_circuit_measures_x_on_ancilla() { let vd = VirtualDistillation::new(Circuit::new(1), 2).unwrap(); let observed_values = vd .run_denominator_circuit(128, &|denominator, hamiltonian, shots| { let denominator_ops = denominator.operations(); - assert_eq!(denominator.width(), 2); - assert_eq!(denominator_ops.len(), 1); + assert_eq!(denominator.width(), 3); + assert_eq!(denominator_ops.len(), 2); assert!(matches!( denominator_ops[0].instruction, - Instruction::Standard(StandardGate::SWAP) + Instruction::Standard(StandardGate::H) + )); + assert!(matches!( + denominator_ops[1].instruction, + Instruction::McGate(_) )); - assert!(hamiltonian.is_none()); assert_eq!(shots, Some(128)); + // The denominator observable Tr(rho^M) is X on the ancillary + // qubit with identities everywhere else. + let denominator_hamiltonian = + hamiltonian.expect("denominator must provide a Hamiltonian"); + assert_eq!(denominator_hamiltonian.num_qubits, 3); + assert_eq!(denominator_hamiltonian.terms.len(), 1); + let (term, coeff) = &denominator_hamiltonian.terms[0]; + assert_eq!(*coeff, Complex64::new(1.0, 0.0)); + assert_eq!((term.x[0], term.z[0]), (false, false)); + assert_eq!((term.x[1], term.z[1]), (false, false)); + assert_eq!((term.x[2], term.z[2]), (true, false)); + (1.0, 0.5) }) .unwrap(); @@ -164,19 +300,22 @@ fn test_run_numerator_circuit_passes_hamiltonian_to_estimator() { .run_numerator_circuit(&hamiltonian, 128, &|numerator, hamiltonian_arg, shots| { let numerator_ops = numerator.operations(); - assert_eq!(numerator.width(), 2); - assert_eq!(numerator_ops.len(), 3); - assert!(hamiltonian_arg.is_some()); + assert_eq!(numerator.width(), 3); + assert_eq!(numerator_ops.len(), 4); assert_eq!(shots, Some(128)); - let expanded_hamiltonian = hamiltonian_arg.unwrap(); - assert_eq!(expanded_hamiltonian.num_qubits, 2); + let expanded_hamiltonian = + hamiltonian_arg.expect("numerator must provide a Hamiltonian"); + assert_eq!(expanded_hamiltonian.num_qubits, 3); assert_eq!(expanded_hamiltonian.terms.len(), 1); + // Observable on the first copy, identity on the extra copy, X on + // the ancillary qubit. let (term, coeff) = &expanded_hamiltonian.terms[0]; assert_eq!(*coeff, Complex64::new(1.0, 0.0)); assert_eq!((term.x[0], term.z[0]), (true, false)); - assert_eq!((term.x[1], term.z[1]), (false, true)); + assert_eq!((term.x[1], term.z[1]), (false, false)); + assert_eq!((term.x[2], term.z[2]), (true, false)); (1.0, 0.25) }) @@ -194,21 +333,29 @@ fn test_run_vd_returns_mu_and_var() { .run_vd(&hamiltonian, 3, 2, &|circuit, hamiltonian_arg, shots| { let ops = circuit.operations(); - assert_eq!(ops.len(), 1); + assert_eq!(ops.len(), 2); assert!(matches!( ops[0].instruction, - Instruction::Standard(StandardGate::SWAP) + Instruction::Standard(StandardGate::H) )); + assert!(matches!(ops[1].instruction, Instruction::McGate(_))); - if let Some(expanded_hamiltonian) = hamiltonian_arg { - assert_eq!(expanded_hamiltonian.num_qubits, 2); - assert_eq!(expanded_hamiltonian.terms.len(), 1); - let (term, _coeff) = &expanded_hamiltonian.terms[0]; + let expanded_hamiltonian = + hamiltonian_arg.expect("numerator and denominator both provide a Hamiltonian"); + assert_eq!(expanded_hamiltonian.num_qubits, 3); + assert_eq!(expanded_hamiltonian.terms.len(), 1); + let (term, _coeff) = &expanded_hamiltonian.terms[0]; + // X on the ancillary qubit in both numerator and denominator. + assert_eq!((term.x[2], term.z[2]), (true, false)); + + if (term.x[0], term.z[0]) != (false, false) { + // Numerator: the observable acts on the first copy. assert_eq!((term.x[0], term.z[0]), (false, true)); - assert_eq!((term.x[1], term.z[1]), (false, true)); assert_eq!(shots, Some(3)); (1.5, 0.25) } else { + // Denominator: identities on all copy qubits. + assert_eq!((term.x[1], term.z[1]), (false, false)); assert_eq!(shots, Some(2)); (2.0, 1.0) } @@ -225,11 +372,11 @@ fn test_run_vd_forwards_zero_samples_to_estimator() { let hamiltonian = single_qubit_z_hamiltonian(); let (mu_vd, var_vd) = vd .run_vd(&hamiltonian, 0, 0, &|_circuit, hamiltonian_arg, shots| { - if hamiltonian_arg.is_some() { - assert_eq!(shots, Some(0)); + assert_eq!(shots, Some(0)); + let term = &hamiltonian_arg.unwrap().terms[0].0; + if (term.x[0], term.z[0]) != (false, false) { (1.0, 0.5) } else { - assert_eq!(shots, Some(0)); (2.0, 1.0) } }) @@ -269,7 +416,8 @@ fn test_run_vd_rejects_zero_denominator_mean() { let hamiltonian = single_qubit_z_hamiltonian(); let err = vd .run_vd(&hamiltonian, 2, 2, &|_circuit, hamiltonian_arg, _shots| { - if hamiltonian_arg.is_some() { + let term = &hamiltonian_arg.unwrap().terms[0].0; + if (term.x[0], term.z[0]) != (false, false) { (1.0, 0.0) } else { (0.0, 0.0) @@ -279,3 +427,56 @@ fn test_run_vd_rejects_zero_denominator_mean() { assert!(matches!(err, ErrorMitigationError::ZeroDenominatorMean)); } + +#[test] +fn test_vd_exact_simulation_recovers_sign_on_excited_state() { + // Preparing |1> and measuring Z: virtual distillation must return -1. + let mut circuit = Circuit::new(1); + circuit.x(Qubit::new(0)).unwrap(); + + let vd = VirtualDistillation::new(circuit, 2).unwrap(); + let hamiltonian = single_qubit_z_hamiltonian(); + let (mu_vd, _) = vd.run_vd(&hamiltonian, 0, 0, &exact_estimator).unwrap(); + + assert!((mu_vd + 1.0).abs() < 1e-12); +} + +#[test] +fn test_vd_exact_simulation_on_rotated_pure_state() { + // Pure states are invariant under distillation: VD returns the exact + // expectation value = cos(theta). + let theta = 0.7; + let mut circuit = Circuit::new(1); + circuit.ry(Qubit::new(0), theta).unwrap(); + + for copies in [2, 3] { + let vd = VirtualDistillation::new(circuit.clone(), copies).unwrap(); + let hamiltonian = single_qubit_z_hamiltonian(); + let (mu_vd, _) = vd.run_vd(&hamiltonian, 0, 0, &exact_estimator).unwrap(); + + assert!((mu_vd - theta.cos()).abs() < 1e-12); + } +} + +#[test] +fn test_vd_mitigates_depolarizing_noise() { + let p = 0.1; + let mut circuit = Circuit::new(1); + circuit.x(Qubit::new(0)).unwrap(); + + let vd = VirtualDistillation::new(circuit, 2).unwrap(); + let hamiltonian = single_qubit_z_hamiltonian(); + let (mu_vd, _) = vd + .run_vd(&hamiltonian, 0, 0, &depolarizing_estimator(p)) + .unwrap(); + + // Depolarized single-copy state rho = a|1><1| + b|0><0|; VD with M = 2 + // estimates Tr(Z rho^2) / Tr(rho^2). + let a = 1.0 - 2.0 * p / 3.0; + let b = 2.0 * p / 3.0; + let unmitigated = b - a; + let expected_vd = (b * b - a * a) / (a * a + b * b); + + assert!((mu_vd - expected_vd).abs() < 1e-12); + assert!((mu_vd + 1.0).abs() < (unmitigated + 1.0).abs()); +} diff --git a/crates/cqlib-core/src/error_mitigation/zne_mitigation.rs b/crates/cqlib-core/src/error_mitigation/zne_mitigation.rs index 33ec9ce4..5223ca3e 100644 --- a/crates/cqlib-core/src/error_mitigation/zne_mitigation.rs +++ b/crates/cqlib-core/src/error_mitigation/zne_mitigation.rs @@ -348,6 +348,7 @@ impl ZNEMitigation { fn fold_all(&self, level: usize) -> Result { let mut folded = Circuit::from_qubits(self.circuit.qubits())?; + folded.set_global_phase(self.circuit.global_phase()); let inverse = self.circuit.inverse()?; self.append_circuit_ops(&mut folded, &self.circuit)?; @@ -366,6 +367,7 @@ impl ZNEMitigation { ) -> Result { let gate_names: HashSet = gate_set.iter().map(Instruction::name).collect(); let mut folded = Circuit::from_qubits(self.circuit.qubits())?; + folded.set_global_phase(self.circuit.global_phase()); for op in self.circuit.operations() { self.append_operation(&mut folded, &self.circuit, op)?; diff --git a/crates/cqlib-core/src/error_mitigation/zne_mitigation_test.rs b/crates/cqlib-core/src/error_mitigation/zne_mitigation_test.rs index 282cd262..4ded2ee0 100644 --- a/crates/cqlib-core/src/error_mitigation/zne_mitigation_test.rs +++ b/crates/cqlib-core/src/error_mitigation/zne_mitigation_test.rs @@ -347,3 +347,30 @@ fn test_extrapolate_api_exponential() { .unwrap(); assert!((extrapolated - a).abs() < 1e-10); } + +#[test] +fn folding_preserves_full_matrix_including_global_phase() { + use crate::circuit::Parameter; + for gates in [false, true] { + let mut c = Circuit::from_qubits(vec![Qubit::new(5)]).unwrap(); + c.set_global_phase(Parameter::from(0.37)); + if gates { + c.h(Qubit::new(5)).unwrap(); + c.t(Qubit::new(5)).unwrap(); + } + let expected = c.to_matrix(None).unwrap(); + let zne = ZNEMitigation::new(c, vec![0, 1, 2]); + let selected = [Instruction::Standard(StandardGate::H)]; + for selection in [None, Some(selected.as_slice()), Some([].as_slice())] { + for folded in zne.fold_circuits(selection).unwrap() { + let actual = folded.to_matrix(None).unwrap(); + assert!( + actual + .iter() + .zip(expected.iter()) + .all(|(a, b)| (*a - *b).norm() < 1e-12) + ); + } + } + } +} diff --git a/crates/cqlib-core/src/ir/qasm2/dump.rs b/crates/cqlib-core/src/ir/qasm2/dump.rs index 03af805a..0af09384 100644 --- a/crates/cqlib-core/src/ir/qasm2/dump.rs +++ b/crates/cqlib-core/src/ir/qasm2/dump.rs @@ -69,7 +69,7 @@ //! loading the generated OpenQASM 2.0 does not restore that phase. use crate::circuit::gate::{ - CircuitGate, ClassicalDataOp, Directive, Instruction, StandardGate, UnitaryGate, + CircuitGate, ClassicalDataOp, Directive, Instruction, MCGate, StandardGate, UnitaryGate, }; use crate::circuit::operation::Operation; use crate::circuit::parameter::Parameter; @@ -260,6 +260,9 @@ pub fn to_path>(circuit: &Circuit, path: P) -> Result<(), QasmDum } /// Dumps a circuit to a string in OpenQASM 2.0 format. +/// +/// Top-level qubits are mapped densely in ascending numeric identifier order, +/// matching [`Circuit::to_matrix`] with its default qubit order. pub fn dumps(circuit: &Circuit) -> Result { let mut output = String::new(); writeln!( @@ -285,21 +288,16 @@ pub fn dumps(circuit: &Circuit) -> Result { writeln!(&mut output)?; - // Pass 0: Collect and output used extended standard gate definitions - let mut used_standard_gates = HashSet::new(); - collect_used_standard_gates(circuit, &mut used_standard_gates); + // Pass 0: Collect actual output names, including those emitted by MCGate. + let mut used_gate_names = HashSet::new(); + collect_used_gate_names(circuit, &mut used_gate_names); let extended_gates = [ - StandardGate::CRX, - StandardGate::CRY, - StandardGate::RZZ, - StandardGate::RXX, - StandardGate::RYY, - StandardGate::RZX, + "crx", "cry", "rzz", "rxx", "ryy", "rzx", "swap", "fsim", "cswap", ]; for gate in extended_gates { - if used_standard_gates.contains(&gate) + if used_gate_names.contains(gate) && let Some(def) = get_extended_gate_definition(gate) { writeln!(&mut output, "{}", def)?; @@ -322,6 +320,19 @@ pub fn dumps(circuit: &Circuit) -> Result { &mut has_delay, )?; + // A helper definition and a user definition cannot share a QASM name. + for name in extended_gates { + if used_gate_names.contains(name) + && (defined_gates.contains_key(name) + || unitary_gate_defs.contains_key(name) + || opaque_unitary_gates.contains_key(name)) + { + return Err(QasmDumpError::FormatError(format!( + "Gate name '{name}' conflicts with a required OpenQASM 2.0 extension definition" + ))); + } + } + // Output CircuitGate definitions for gate in defined_gates.values() { dump_gate_definition(gate, &mut output)?; @@ -347,10 +358,13 @@ pub fn dumps(circuit: &Circuit) -> Result { } // Pass 2: Main circuit - // Map Qubit(i) -> "q[i]" + // Numeric identifiers need not be contiguous or match storage order. + // Preserve the default matrix basis while keeping the register width N. let mut qubit_map: HashMap = HashMap::new(); - for q in circuit.qubits() { - qubit_map.insert(q, format!("q[{}]", q.index())); + let mut qubits = circuit.qubits(); + qubits.sort_unstable(); + for (index, q) in qubits.into_iter().enumerate() { + qubit_map.insert(q, format!("q[{index}]")); } // Top-level parameter resolution is direct (Parameter objects are used as is) @@ -596,7 +610,7 @@ fn dump_unitary_gate_definition( // Body context let mut body_qubit_map = HashMap::new(); let inner_circuit = &frozen_circuit.circuit; - for (i, q) in inner_circuit.qubits().iter().enumerate() { + for (i, q) in frozen_circuit.qubits_in_numeric_order().iter().enumerate() { body_qubit_map.insert(*q, format!("q{}", i)); } @@ -987,6 +1001,10 @@ fn resolve_param( Ok(param) } +fn format_parameter(param: &Parameter) -> String { + param.to_string().replace('π', "pi") +} + fn format_params( op: &Operation, circuit: &Circuit, @@ -997,8 +1015,7 @@ fn format_params( } let params = (0..op.params.len()) .map(|index| { - resolve_param(op, index, circuit, param_map) - .map(|param| param.to_string().replace("π", "pi")) + resolve_param(op, index, circuit, param_map).map(|param| format_parameter(¶m)) }) .collect::, _>>()?; Ok(format!("({})", params.join(","))) @@ -1062,22 +1079,22 @@ fn dump_standard_gate( match gate { StandardGate::X2P => { writeln!(output, "// x2p {}", mapped_qs[0])?; - writeln!(output, "rx(pi/2) {}", mapped_qs[0])?; + writeln!(output, "rx(pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::X2M => { writeln!(output, "// x2m {}", mapped_qs[0])?; - writeln!(output, "rx(-pi/2) {}", mapped_qs[0])?; + writeln!(output, "rx(-pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::Y2P => { writeln!(output, "// y2p {}", mapped_qs[0])?; - writeln!(output, "ry(pi/2) {}", mapped_qs[0])?; + writeln!(output, "ry(pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::Y2M => { writeln!(output, "// y2m {}", mapped_qs[0])?; - writeln!(output, "ry(-pi/2) {}", mapped_qs[0])?; + writeln!(output, "ry(-pi/2) {};", mapped_qs[0])?; return Ok(()); } StandardGate::XY2P => { @@ -1086,10 +1103,10 @@ fn dump_standard_gate( let p3 = theta.clone() - Parameter::pi() / 2.0; let q_str = &mapped_qs[0]; - writeln!(output, "// xy2p({}) {}", theta, q_str)?; - writeln!(output, "rz({}) {}", p1, q_str)?; - writeln!(output, "ry(pi/2) {}", q_str)?; - writeln!(output, "rz({}) {}", p3, q_str)?; + writeln!(output, "// xy2p({}) {}", format_parameter(&theta), q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&p1), q_str)?; + writeln!(output, "ry(pi/2) {};", q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&p3), q_str)?; return Ok(()); } StandardGate::XY2M => { @@ -1098,10 +1115,10 @@ fn dump_standard_gate( let m3 = theta.clone() + Parameter::pi() / 2.0; let q_str = &mapped_qs[0]; - writeln!(output, "// xy2m({}) {}", theta, q_str)?; - writeln!(output, "rz({}) {}", m1, q_str)?; - writeln!(output, "ry(pi/2) {}", q_str)?; - writeln!(output, "rz({}) {}", m3, q_str)?; + writeln!(output, "// xy2m({}) {}", format_parameter(&theta), q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&m1), q_str)?; + writeln!(output, "ry(pi/2) {};", q_str)?; + writeln!(output, "rz({}) {};", format_parameter(&m3), q_str)?; return Ok(()); } StandardGate::XY => { @@ -1110,18 +1127,13 @@ fn dump_standard_gate( let lambda: Parameter = Parameter::pi() / 2.0 - theta.clone(); let q_str = &mapped_qs[0]; - writeln!( - output, - "// xy({}) {}", - theta.to_string().replace("π", "pi"), - q_str - )?; + writeln!(output, "// xy({}) {}", format_parameter(&theta), q_str)?; writeln!( output, "u3({},{},{}) {};", - Parameter::pi().to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&Parameter::pi()), + format_parameter(&phase), + format_parameter(&lambda), q_str )?; return Ok(()); @@ -1136,16 +1148,16 @@ fn dump_standard_gate( writeln!( output, "// rxy({},{}) {}", - theta.to_string().replace("π", "pi"), - phi.to_string().replace("π", "pi"), + format_parameter(&theta), + format_parameter(&phi), q_str )?; writeln!( output, "u3({},{},{}) {};", - theta.to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&theta), + format_parameter(&phase), + format_parameter(&lambda), q_str )?; return Ok(()); @@ -1195,8 +1207,25 @@ fn dump_directive( Ok(()) } +fn qasm2_mc_gate_name(mc_gate: &MCGate) -> Option<&'static str> { + match (mc_gate.num_ctrl_qubits(), mc_gate.base_gate()) { + (1, StandardGate::X) => Some("cx"), + (1, StandardGate::Z) => Some("cz"), + (1, StandardGate::Y) => Some("cy"), + (1, StandardGate::H) => Some("ch"), + (1, StandardGate::RX) => Some("crx"), + (1, StandardGate::RY) => Some("cry"), + (1, StandardGate::RZ) => Some("crz"), + (1, StandardGate::Phase) => Some("cu1"), + (1, StandardGate::CX) => Some("ccx"), + (1, StandardGate::SWAP) => Some("cswap"), + (2, StandardGate::X) => Some("ccx"), + _ => None, + } +} + fn dump_mc_gate( - mc_gate: &crate::circuit::gate::MCGate, + mc_gate: &MCGate, op: &Operation, circuit: &Circuit, output: &mut String, @@ -1206,25 +1235,12 @@ fn dump_mc_gate( let num_ctrl = mc_gate.num_ctrl_qubits(); let base = mc_gate.base_gate(); - let name = match (num_ctrl, base) { - (1, StandardGate::X) => "cx", - (1, StandardGate::Z) => "cz", - (1, StandardGate::Y) => "cy", - (1, StandardGate::H) => "ch", - (1, StandardGate::RX) => "crx", - (1, StandardGate::RY) => "cry", - (1, StandardGate::RZ) => "crz", - (1, StandardGate::Phase) => "cu1", - (1, StandardGate::CX) => "ccx", - (1, StandardGate::SWAP) => "cswap", - (2, StandardGate::X) => "ccx", - _ => { - return Err(QasmDumpError::FormatError(format!( - "Unsupported MCGate: {} controls on {}", - num_ctrl, base - ))); - } - }; + let name = qasm2_mc_gate_name(mc_gate).ok_or_else(|| { + QasmDumpError::FormatError(format!( + "Unsupported MCGate: {} controls on {}", + num_ctrl, base + )) + })?; let params_str = format_params(op, circuit, param_map)?; let mapped_qs = map_qubits(op, qubit_map); @@ -1233,58 +1249,58 @@ fn dump_mc_gate( Ok(()) } -fn collect_used_standard_gates(circuit: &Circuit, used_gates: &mut HashSet) { - collect_used_standard_gates_from_operations(circuit.operations(), used_gates); +fn collect_used_gate_names(circuit: &Circuit, used_gates: &mut HashSet<&'static str>) { + collect_used_gate_names_from_operations(circuit.operations(), used_gates); } -fn collect_used_standard_gates_from_operations( +fn collect_used_gate_names_from_operations( operations: &[Operation], - used_gates: &mut HashSet, + used_gates: &mut HashSet<&'static str>, ) { for op in operations { match &op.instruction { Instruction::Standard(sg) => { - used_gates.insert(*sg); + used_gates.extend(qasm2_builtin_gate_name(*sg)); + } + Instruction::McGate(mc_gate) => { + used_gates.extend(qasm2_mc_gate_name(mc_gate)); } Instruction::CircuitGate(cg) => { - collect_used_standard_gates(&cg.circuit.circuit, used_gates); + collect_used_gate_names(&cg.circuit.circuit, used_gates); } Instruction::UnitaryGate(ug) => { if let Some(fc) = ug.circuit() { - collect_used_standard_gates(&fc.circuit, used_gates); + collect_used_gate_names(&fc.circuit, used_gates); } } Instruction::ClassicalControl(control) => match control { ClassicalControlOp::If(if_op) => { - collect_used_standard_gates_from_operations( + collect_used_gate_names_from_operations( if_op.then_body().operations(), used_gates, ); if let Some(body) = if_op.else_body() { - collect_used_standard_gates_from_operations(body.operations(), used_gates); + collect_used_gate_names_from_operations(body.operations(), used_gates); } } ClassicalControlOp::While(while_op) => { - collect_used_standard_gates_from_operations( + collect_used_gate_names_from_operations( while_op.body().operations(), used_gates, ); } ClassicalControlOp::For(for_op) => { - collect_used_standard_gates_from_operations( - for_op.body().operations(), - used_gates, - ); + collect_used_gate_names_from_operations(for_op.body().operations(), used_gates); } ClassicalControlOp::Switch(switch_op) => { for case in switch_op.cases() { - collect_used_standard_gates_from_operations( + collect_used_gate_names_from_operations( case.body().operations(), used_gates, ); } if let Some(body) = switch_op.default() { - collect_used_standard_gates_from_operations(body.operations(), used_gates); + collect_used_gate_names_from_operations(body.operations(), used_gates); } } ClassicalControlOp::Break | ClassicalControlOp::Continue => {} @@ -1475,9 +1491,9 @@ fn operation_to_qasm( let lambda: Parameter = Parameter::pi() / 2.0 - theta; return Ok(format!( "u3({},{},{}) {}", - Parameter::pi().to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&Parameter::pi()), + format_parameter(&phase), + format_parameter(&lambda), mapped_qs[0] )); } @@ -1488,9 +1504,9 @@ fn operation_to_qasm( let lambda: Parameter = Parameter::pi() / 2.0 - phi; return Ok(format!( "u3({},{},{}) {}", - theta.to_string().replace("π", "pi"), - phase.to_string().replace("π", "pi"), - lambda.to_string().replace("π", "pi"), + format_parameter(&theta), + format_parameter(&phase), + format_parameter(&lambda), mapped_qs[0] )); } @@ -1507,25 +1523,12 @@ fn operation_to_qasm( Instruction::McGate(mc_gate) => { let num_ctrl = mc_gate.num_ctrl_qubits(); let base = mc_gate.base_gate(); - let name = match (num_ctrl, base) { - (1, StandardGate::X) => "cx", - (2, StandardGate::X) => "ccx", - (1, StandardGate::Z) => "cz", - (1, StandardGate::Y) => "cy", - (1, StandardGate::H) => "ch", - (1, StandardGate::CX) => "ccx", - (1, StandardGate::RX) => "crx", - (1, StandardGate::RY) => "cry", - (1, StandardGate::RZ) => "crz", - (1, StandardGate::SWAP) => "cswap", - (1, StandardGate::Phase) => "cu1", - _ => { - return Err(QasmDumpError::FormatError(format!( - "Unsupported multi-controlled gate: {}-controlled {:?}", - num_ctrl, base - ))); - } - }; + let name = qasm2_mc_gate_name(mc_gate).ok_or_else(|| { + QasmDumpError::FormatError(format!( + "Unsupported multi-controlled gate: {}-controlled {:?}", + num_ctrl, base + )) + })?; let params_str = format_params(op, circuit, param_map)?; let mapped_qs = map_qubits(op, qubit_map); Ok(format!("{}{} {}", name, params_str, mapped_qs.join(","))) @@ -1567,22 +1570,30 @@ fn operation_to_qasm( } } -fn get_extended_gate_definition(gate: StandardGate) -> Option<&'static str> { +// Definitions use only the original qelib1.inc, so no implicit extension +// dependencies (or additional dependency ordering) are needed. +fn get_extended_gate_definition(gate: &str) -> Option<&'static str> { match gate { - StandardGate::CRX => { + "crx" => { Some("gate crx(theta) a,b { h b;rz(theta/2) b; cx a,b; rz(-theta/2) b; cx a,b; h b;}") } - StandardGate::CRY => { - Some("gate cry(theta) a,b { ry(theta/2) b; cx a,b; ry(-theta/2) b; cx a,b; }") - } - StandardGate::RZZ => Some("gate rzz(theta) a,b { cx a,b; rz(theta) b; cx a,b; }"), - StandardGate::RXX => { - Some("gate rxx(theta) a,b { h a; h b; cx a,b; rz(theta) b; cx a,b; h a; h b; }") - } - StandardGate::RYY => Some( + "cry" => Some("gate cry(theta) a,b { ry(theta/2) b; cx a,b; ry(-theta/2) b; cx a,b; }"), + "rzz" => Some("gate rzz(theta) a,b { cx a,b; rz(theta) b; cx a,b; }"), + "rxx" => Some("gate rxx(theta) a,b { h a; h b; cx a,b; rz(theta) b; cx a,b; h a; h b; }"), + "ryy" => Some( "gate ryy(theta) a,b { rx(pi/2) a; rx(pi/2) b; cx a,b; rz(theta) b; cx a,b; rx(-pi/2) a; rx(-pi/2) b; }", ), - StandardGate::RZX => Some("gate rzx(theta) a,b { h b; cx a,b; rz(theta) b; cx a,b; h b; }"), + "rzx" => Some("gate rzx(theta) a,b { h b; cx a,b; rz(theta) b; cx a,b; h b; }"), + "swap" => Some("gate swap a,b { cx a,b; cx b,a; cx a,b; }"), + "cswap" => Some("gate cswap c,a,b { cx b,a; ccx c,a,b; cx b,a; }"), + // FSIM(theta,phi) = RXX(theta) RYY(theta) CP(-phi), inlined to + // keep the definition independent of other extension definitions. + "fsim" => Some(concat!( + "gate fsim(theta,phi) a,b { ", + "h a; h b; cx a,b; rz(theta) b; cx a,b; h a; h b; ", + "rx(pi/2) a; rx(pi/2) b; cx a,b; rz(theta) b; cx a,b; ", + "rx(-pi/2) a; rx(-pi/2) b; cu1(-phi) a,b; }" + )), _ => None, } } diff --git a/crates/cqlib-core/src/ir/qasm2/dump_test.rs b/crates/cqlib-core/src/ir/qasm2/dump_test.rs index b2958e3e..06520d7b 100644 --- a/crates/cqlib-core/src/ir/qasm2/dump_test.rs +++ b/crates/cqlib-core/src/ir/qasm2/dump_test.rs @@ -14,7 +14,8 @@ use crate::circuit::gate::circuit_gate::FrozenCircuit; use crate::circuit::gate::{StandardGate, UnitaryGate}; use crate::circuit::parameter::Parameter; use crate::circuit::symbolic_matrix::standard_gate_symbolic_matrix; -use crate::circuit::{Circuit, ClassicalExpr, ClassicalType, Instruction, Qubit}; +use crate::circuit::test_utils::assert_matrix_approx_eq; +use crate::circuit::{Circuit, ClassicalExpr, ClassicalType, Instruction, ParameterValue, Qubit}; use crate::ir::qasm2::dump::{QasmDumpError, dump, dumps, to_path, to_string}; use crate::ir::qasm2::load::loads; use std::fs; @@ -69,6 +70,289 @@ fn verify_qasm_roundtrip(qasm: &str, expected_qubits: usize) { ); } +const HALF_ROTATION_GATES: [StandardGate; 6] = [ + StandardGate::X2P, + StandardGate::X2M, + StandardGate::Y2P, + StandardGate::Y2M, + StandardGate::XY2P, + StandardGate::XY2M, +]; + +fn half_rotation_circuit(gate: StandardGate, axis: Parameter) -> Circuit { + let mut circuit = Circuit::new(1); + let params: Vec = if gate.num_params() == 0 { + vec![] + } else { + vec![axis.into()] + }; + circuit + .append(Instruction::Standard(gate), [Qubit::new(0)], params, None) + .unwrap(); + circuit +} + +fn assert_qasm_unitary_matches(qasm: &str, circuit: &Circuit, allow_global_phase: bool) { + assert!(qasm.is_ascii(), "Expected ASCII QASM:\n{qasm}"); + let parsed = loads(qasm).unwrap_or_else(|error| panic!("{error}\n{qasm}")); + assert_eq!(parsed.num_qubits(), circuit.num_qubits()); + let mut expected = circuit.to_matrix(None).unwrap(); + let actual = parsed.to_matrix(None).unwrap(); + if allow_global_phase { + // QASM2 cannot preserve arbitrary global phase. Compare a single phase + // for the entire unitary, never a separate phase for each input column. + let (index, pivot) = expected + .indexed_iter() + .find(|(_, z)| z.norm() > 0.1) + .unwrap(); + let ratio = actual[index] / *pivot; + assert!((ratio.norm() - 1.0).abs() < 1e-10, "{qasm}"); + expected.mapv_inplace(|z| z * ratio); + } + assert_matrix_approx_eq(&actual, &expected, 1e-10); +} + +/// Force extension calls through their emitted definitions instead of the +/// loader's implicit Cqlib builtins. This also checks the definition bodies. +fn without_implicit_extension_gates(qasm: &str) -> String { + regex::Regex::new(r"\b(crx|cry|rxx|ryy|rzz|rzx|swap|cswap|fsim)\b") + .unwrap() + .replace_all(qasm, "exported_$1") + .into_owned() +} + +fn extension_test_circuit(gate: StandardGate, controlled: bool, values: [f64; 2]) -> Circuit { + let instruction = if controlled { + Instruction::McGate(Box::new(crate::circuit::gate::MCGate::new(1, gate))) + } else { + Instruction::Standard(gate) + }; + let mut circuit = Circuit::new(gate.num_qubits() + usize::from(controlled)); + let params: Vec = values[..gate.num_params()] + .iter() + .copied() + .map(Into::into) + .collect(); + circuit + .append(instruction, circuit.qubits(), params, None) + .unwrap(); + circuit +} + +fn assert_portable_gate_definition(gate: StandardGate, controlled: bool) { + for values in [ + [0.0, 0.0], + [0.731, -1.219], + [-std::f64::consts::PI, std::f64::consts::FRAC_PI_2], + ] { + let circuit = extension_test_circuit(gate, controlled, values); + let qasm = dumps(&circuit).unwrap(); + assert_qasm_unitary_matches(&without_implicit_extension_gates(&qasm), &circuit, false); + } +} + +#[test] +fn portable_qasm2_standard_swap_definition() { + assert_portable_gate_definition(StandardGate::SWAP, false); +} + +#[test] +fn portable_qasm2_standard_fsim_definition() { + assert_portable_gate_definition(StandardGate::FSIM, false); +} + +#[test] +fn portable_qasm2_controlled_rx_definition() { + assert_portable_gate_definition(StandardGate::RX, true); +} + +#[test] +fn portable_qasm2_controlled_ry_definition() { + assert_portable_gate_definition(StandardGate::RY, true); +} + +#[test] +fn portable_qasm2_controlled_swap_definition() { + assert_portable_gate_definition(StandardGate::SWAP, true); +} + +#[test] +fn portable_qasm2_standard_controlled_rotations_still_define_gates() { + assert_portable_gate_definition(StandardGate::CRX, false); + assert_portable_gate_definition(StandardGate::CRY, false); +} + +#[test] +fn portable_qasm2_sparse_qubits_preserve_numeric_basis_and_width() { + let qubits = [9, 2, 5].map(Qubit::new); + let mut circuit = Circuit::from_qubits(qubits.to_vec()).unwrap(); + circuit.x(qubits[0]).unwrap(); + circuit.cx(qubits[0], qubits[2]).unwrap(); + circuit.validate().unwrap(); + + let qasm = dumps(&circuit).unwrap(); + assert_qasm_unitary_matches(&qasm, &circuit, false); + let path = unique_temp_path("sparse_qubits"); + dump(&circuit, &path).unwrap(); + assert_eq!(fs::read_to_string(&path).unwrap(), qasm); + fs::remove_file(path).unwrap(); +} + +#[test] +fn portable_qasm2_dense_qubits_in_storage_order_keep_numeric_basis() { + let qubits = [2, 0, 1].map(Qubit::new); + let mut circuit = Circuit::from_qubits(qubits.to_vec()).unwrap(); + circuit.x(qubits[0]).unwrap(); + circuit.cx(qubits[0], qubits[2]).unwrap(); + assert_qasm_unitary_matches(&dumps(&circuit).unwrap(), &circuit, false); +} + +#[test] +fn portable_qasm2_sparse_qubits_map_measurement_reset_and_if() { + let qubits = [9, 2, 5].map(Qubit::new); + let mut circuit = Circuit::from_qubits(qubits.to_vec()).unwrap(); + circuit.barrier(qubits.to_vec()).unwrap(); + circuit.reset(qubits[0]).unwrap(); + let measured = circuit.measure(qubits[2]).unwrap(); + circuit + .if_( + ClassicalExpr::bit_to_bool(measured.expr()).unwrap(), + |body| { + body.x(qubits[1])?; + Ok(()) + }, + ) + .unwrap(); + let qasm = dumps(&circuit).unwrap(); + assert_qasm_contains_ordered( + &qasm, + &[ + "qreg q[3];", + "barrier q[2],q[0],q[1];", + "reset q[2];", + "measure q[1] -> v0[0];", + "if (v0 == 1) x q[0];", + ], + ); + verify_qasm_roundtrip(&qasm, 3); +} + +#[test] +fn portable_qasm2_definitions_in_custom_gate_bodies() { + for (gate, controlled) in [ + (StandardGate::RX, true), + (StandardGate::RY, true), + (StandardGate::SWAP, true), + (StandardGate::SWAP, false), + (StandardGate::FSIM, false), + ] { + let inner = extension_test_circuit(gate, controlled, [0.731, -1.219]); + let width = inner.num_qubits(); + let custom = inner.clone().to_gate("wrapped_custom").unwrap(); + let unitary = UnitaryGate::new("wrapped_unitary", width as u16, 0) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + for instruction in [custom, Instruction::UnitaryGate(Box::new(unitary))] { + let mut outer = Circuit::new(width); + outer + .append(instruction, outer.qubits(), std::iter::empty(), None) + .unwrap(); + let qasm = dumps(&outer).unwrap(); + assert_qasm_unitary_matches(&without_implicit_extension_gates(&qasm), &outer, false); + } + } +} + +#[test] +fn portable_qasm2_definitions_in_if_bodies() { + for (gate, controlled) in [ + (StandardGate::RX, true), + (StandardGate::RY, true), + (StandardGate::SWAP, true), + (StandardGate::SWAP, false), + (StandardGate::FSIM, false), + ] { + let inner = extension_test_circuit(gate, controlled, [0.731, -1.219]); + let operation = &inner.operations()[0]; + let mut outer = Circuit::new(inner.num_qubits()); + let measured = outer.measure(Qubit::new(0)).unwrap(); + outer + .if_( + ClassicalExpr::bit_to_bool(measured.expr()).unwrap(), + |body| { + body.append( + operation.instruction.clone(), + operation.qubits.iter().copied(), + [0.731, -1.219][..gate.num_params()] + .iter() + .copied() + .map(ParameterValue::from), + None, + )?; + Ok(()) + }, + ) + .unwrap(); + let qasm = without_implicit_extension_gates(&dumps(&outer).unwrap()); + verify_qasm_roundtrip(&qasm, outer.num_qubits()); + // The extension must be defined before the conditional invocation. + assert_qasm_contains_ordered(&qasm, &["gate exported_", "if (v0 == 1) exported_"]); + } +} + +#[test] +fn portable_qasm2_mixed_standard_and_mcgate_define_rotation_once() { + let mut circuit = extension_test_circuit(StandardGate::RX, true, [0.731, 0.0]); + circuit.crx(Qubit::new(0), Qubit::new(1), -0.2).unwrap(); + let qasm = dumps(&circuit).unwrap(); + assert_eq!(qasm.matches("gate crx(").count(), 1, "{qasm}"); + assert_qasm_unitary_matches(&without_implicit_extension_gates(&qasm), &circuit, false); +} + +#[test] +fn portable_qasm2_extension_definition_conflicts_are_rejected() { + for (name, gate, controlled) in [ + ("swap", StandardGate::SWAP, false), + ("fsim", StandardGate::FSIM, false), + ("cswap", StandardGate::SWAP, true), + ] { + let mut inner = Circuit::new(1); + inner.x(Qubit::new(0)).unwrap(); + let custom = inner.clone().to_gate(name).unwrap(); + let unitary = UnitaryGate::new(name, 1, 0) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + let opaque = UnitaryGate::new(name, 1, 0); + for instruction in [ + custom, + Instruction::UnitaryGate(Box::new(unitary)), + Instruction::UnitaryGate(Box::new(opaque)), + ] { + // A custom definition alone must remain valid even if its name + // happens to match an unused standard extension. + let mut custom_only = Circuit::new(1); + custom_only + .append( + instruction.clone(), + [Qubit::new(0)], + std::iter::empty(), + None, + ) + .unwrap(); + assert!(dumps(&custom_only).is_ok()); + + let mut circuit = extension_test_circuit(gate, controlled, [0.731, -1.219]); + circuit + .append(instruction, [Qubit::new(0)], std::iter::empty(), None) + .unwrap(); + assert!(matches!( + dumps(&circuit), + Err(QasmDumpError::FormatError(message)) if message.contains(name) + )); + } + } +} + /// Simple contains check (for backwards compatibility) fn assert_qasm_contains(qasm: &str, expected_lines: &[&str]) { for &line in expected_lines { @@ -1530,15 +1814,241 @@ fn test_dump_x2p_x2m_y2p_y2m() { &qasm, &[ "// x2p q[0]", - "rx(pi/2) q[0]", + "rx(pi/2) q[0];", "// x2m q[0]", - "rx(-pi/2) q[0]", + "rx(-pi/2) q[0];", "// y2p q[0]", - "ry(pi/2) q[0]", + "ry(pi/2) q[0];", "// y2m q[0]", - "ry(-pi/2) q[0]", + "ry(-pi/2) q[0];", ], ); + assert_qasm_unitary_matches(&qasm, &circuit, false); +} + +#[test] +fn half_rotations_roundtrip_individually_with_numeric_and_pi_axes() { + let axes = [ + Parameter::from(0.0), + Parameter::from(0.731), + Parameter::from(-1.219), + Parameter::pi() / 2.0, + -Parameter::pi() / 3.0, + Parameter::pi() * 4.0 + 0.25, + ]; + for gate in HALF_ROTATION_GATES { + for axis in &axes[..if gate.num_params() == 0 { + 1 + } else { + axes.len() + }] { + let circuit = half_rotation_circuit(gate, axis.clone()); + let qasm = dumps(&circuit).unwrap(); + assert_qasm_unitary_matches(&qasm, &circuit, false); + let statements: Vec<_> = qasm + .lines() + .filter(|line| { + line.starts_with("rx(") || line.starts_with("ry(") || line.starts_with("rz(") + }) + .collect(); + assert_eq!(statements.len(), if gate.num_params() == 0 { 1 } else { 3 }); + assert!( + statements.iter().all(|line| line.ends_with(';')), + "{gate:?}: {qasm}" + ); + } + } +} + +#[test] +fn half_rotations_roundtrip_in_entangled_circuit() { + let mut circuit = Circuit::new(3); + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(2)).unwrap(); + for (index, gate) in HALF_ROTATION_GATES.into_iter().enumerate() { + let qubit = Qubit::new((index % 3) as u32); + circuit + .compose( + &half_rotation_circuit(gate, Parameter::pi() / 7.0), + Some(&[qubit]), + ) + .unwrap(); + circuit + .cx(qubit, Qubit::new(((index + 1) % 3) as u32)) + .unwrap(); + } + circuit.h(Qubit::new(1)).unwrap(); + circuit.rz(Qubit::new(2), -0.43).unwrap(); + assert_qasm_unitary_matches(&dumps(&circuit).unwrap(), &circuit, false); +} + +#[test] +fn half_rotations_roundtrip_in_parameterized_custom_and_unitary_gates() { + for gate in HALF_ROTATION_GATES { + let inner = half_rotation_circuit( + gate, + Parameter::symbol("theta") / 2.0 + Parameter::pi() / 3.0, + ); + let custom = inner.clone().to_gate("half_rotation").unwrap(); + let unitary = UnitaryGate::new("half_unitary", 1, gate.num_params() as u16) + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + for value in [-1.219, 0.731, std::f64::consts::FRAC_PI_2] { + let params: Vec = if gate.num_params() == 0 { + vec![] + } else { + vec![value.into()] + }; + for instruction in [ + custom.clone(), + Instruction::UnitaryGate(Box::new(unitary.clone())), + ] { + let mut circuit = Circuit::new(2); + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + circuit + .append(instruction, [Qubit::new(1)], params.clone(), None) + .unwrap(); + circuit.h(Qubit::new(1)).unwrap(); + assert_qasm_unitary_matches(&dumps(&circuit).unwrap(), &circuit, false); + } + } + } +} + +#[test] +fn half_rotations_roundtrip_through_file_and_string_aliases() { + use crate::ir::qasm2::load::{from_path, load}; + + for gate in HALF_ROTATION_GATES { + let circuit = half_rotation_circuit(gate, Parameter::pi() / 3.0); + let qasm = dumps(&circuit).unwrap(); + assert_eq!(to_string(&circuit).unwrap(), qasm); + let path = unique_temp_path(&format!("half_rotation_{gate:?}")); + dump(&circuit, &path).unwrap(); + let saved = fs::read_to_string(&path).unwrap(); + assert_eq!(saved, qasm); + assert_qasm_unitary_matches(&saved, &circuit, false); + to_path(&circuit, &path).unwrap(); + for parsed in [load(&path).unwrap(), from_path(&path).unwrap()] { + assert_matrix_approx_eq( + &parsed.to_matrix(None).unwrap(), + &circuit.to_matrix(None).unwrap(), + 1e-10, + ); + } + fs::remove_file(path).unwrap(); + } +} + +#[test] +fn xy_half_rotations_resolve_parameters_and_report_invalid_values() { + use crate::circuit::CircuitParam; + use std::collections::HashMap; + + let qubit = Qubit::new(0); + let qubit_map = HashMap::from([(qubit, "q[0]".to_string())]); + let replacements = HashMap::from([("theta".to_string(), Parameter::pi() / 3.0)]); + for gate in [StandardGate::XY2P, StandardGate::XY2M] { + let circuit = half_rotation_circuit(gate, Parameter::symbol("theta")); + let operation = &circuit.operations()[0]; + let mut qasm = "OPENQASM 2.0;\ninclude \"qelib1.inc\";\nqreg q[1];\n".to_string(); + super::dump_standard_gate( + &gate, + operation, + &circuit, + &mut qasm, + &qubit_map, + &replacements, + ) + .unwrap(); + assert_qasm_unitary_matches( + &qasm, + &half_rotation_circuit(gate, Parameter::pi() / 3.0), + false, + ); + + for invalid in [ + CircuitParam::Index(u32::MAX), + CircuitParam::Fixed(f64::NAN), + CircuitParam::Fixed(f64::INFINITY), + CircuitParam::Fixed(f64::NEG_INFINITY), + ] { + let mut operation = operation.clone(); + operation.params[0] = invalid; + let error = super::dump_standard_gate( + &gate, + &operation, + &circuit, + &mut String::new(), + &qubit_map, + &replacements, + ) + .unwrap_err(); + assert!(matches!(error, QasmDumpError::FormatError(message) + if message.contains("parameter 0") && message.contains(&format!("{gate:?}")))); + } + } +} + +#[test] +fn half_rotations_in_conditional_bodies_remain_explicitly_unsupported() { + for gate in HALF_ROTATION_GATES { + let mut circuit = Circuit::new(2); + let measured = circuit.measure(Qubit::new(0)).unwrap(); + let condition = ClassicalExpr::bit_to_bool(measured.expr()).unwrap(); + circuit + .if_(condition, |body| { + body.compose( + &half_rotation_circuit(gate, Parameter::pi() / 3.0), + Some(&[Qubit::new(1)]), + )?; + Ok(()) + }) + .unwrap(); + assert!( + matches!(dumps(&circuit), Err(QasmDumpError::UnsupportedClassicalControl(message)) + if message.contains(&format!("{gate:?}"))) + ); + } +} + +#[test] +fn every_standard_gate_qasm2_roundtrips_with_documented_phase_policy() { + let parameter_sets = [ + [0.0, 0.0, 0.0], + [0.731, -1.219, 2.031], + [-std::f64::consts::PI, std::f64::consts::FRAC_PI_2, -0.25], + ]; + for &gate in StandardGate::all() { + for values in parameter_sets { + let mut circuit = Circuit::new(3); + let params: Vec = values[..gate.num_params()] + .iter() + .copied() + .map(Into::into) + .collect(); + circuit + .append( + Instruction::Standard(gate), + (0..gate.num_qubits()).map(|index| Qubit::new(index as u32)), + params, + None, + ) + .unwrap(); + let qasm = dumps(&circuit).unwrap(); + if gate == StandardGate::GPhase { + // GPhase is deliberately emitted as a comment, not silently + // treated as a successful phase-preserving roundtrip. + assert!(qasm.contains("// gphase("), "{qasm}"); + let parsed = loads(&qasm).unwrap(); + assert!(parsed.operations().is_empty()); + assert_eq!(parsed.global_phase().evaluate(&None).unwrap(), 0.0); + } else { + assert_qasm_unitary_matches(&qasm, &circuit, !HALF_ROTATION_GATES.contains(&gate)); + } + } + } } #[test] diff --git a/crates/cqlib-core/src/ir/qasm3/dump.rs b/crates/cqlib-core/src/ir/qasm3/dump.rs index 914669cf..a6bd1313 100644 --- a/crates/cqlib-core/src/ir/qasm3/dump.rs +++ b/crates/cqlib-core/src/ir/qasm3/dump.rs @@ -516,6 +516,7 @@ fn dump_gate_definition(gate: &CircuitGate, output: &mut String) -> Result<(), Q for (index, qubit) in gate.circuit.circuit.qubits().iter().copied().enumerate() { qubit_map.insert(qubit, format!("q{index}")); } + dump_global_phase(&gate.circuit.circuit, output, &HashMap::new())?; dump_operations( &gate.circuit.circuit, gate.circuit.circuit.operations(), @@ -549,9 +550,10 @@ fn dump_unitary_gate_definition( .collect(); writeln!(output, "gate {label} {} {{", qubits.join(","))?; let mut qubit_map = HashMap::new(); - for (index, qubit) in frozen.circuit.qubits().iter().copied().enumerate() { + for (index, qubit) in frozen.qubits_in_numeric_order().into_iter().enumerate() { qubit_map.insert(qubit, format!("q{index}")); } + dump_global_phase(&frozen.circuit, output, &HashMap::new())?; dump_operations( &frozen.circuit, frozen.circuit.operations(), diff --git a/crates/cqlib-core/src/ir/qasm3/dump_test.rs b/crates/cqlib-core/src/ir/qasm3/dump_test.rs index 9b93c967..ddd548d5 100644 --- a/crates/cqlib-core/src/ir/qasm3/dump_test.rs +++ b/crates/cqlib-core/src/ir/qasm3/dump_test.rs @@ -862,3 +862,53 @@ fn export_preserves_indexed_constants_and_symbol_substitution() { "(angle0)" ); } + +#[test] +fn nested_gate_global_phase_round_trip() { + let circuit = qasm3_loads( + r#" + OPENQASM 3; + include "stdgates.inc"; + gate fragment(theta) q { gphase(theta); h q; } + gate middle(alpha) q { gphase(0.11); fragment(alpha) q; } + qubit q; + middle(0.37) q; + middle(-0.51) q; + "#, + ) + .unwrap(); + let output = dumps(&circuit).unwrap(); + let loaded = qasm3_loads(&output).unwrap(); + let expected = num_complex::Complex64::from_polar(1.0, 0.08); + for ((row, col), actual) in loaded.to_matrix(None).unwrap().indexed_iter() { + let reference = if row == col { + expected + } else { + num_complex::Complex64::new(0.0, 0.0) + }; + assert!((*actual - reference).norm() < 1e-12, "{output}"); + } + assert!(output.contains("gphase(theta);"), "{output}"); + assert!(output.contains("gphase(0.11);"), "{output}"); +} + +#[test] +fn unitary_definition_global_phase_round_trip() { + use crate::circuit::gate::UnitaryGate; + let mut inner = Circuit::new(1); + inner.h(Qubit::new(0)).unwrap(); + inner.set_global_phase(0.37.into()); + let expected = inner.to_matrix(None).unwrap(); + let gate = UnitaryGate::new("phase_h", 1, 0) + .with_matrix(expected.clone()) + .unwrap() + .with_circuit(Arc::new(FrozenCircuit::new(inner))) + .unwrap(); + let mut circuit = Circuit::new(1); + circuit.unitary(gate, vec![Qubit::new(0)]).unwrap(); + let output = dumps(&circuit).unwrap(); + let loaded = qasm3_loads(&output).unwrap(); + for (actual, expected) in loaded.to_matrix(None).unwrap().iter().zip(expected.iter()) { + assert!((actual - expected).norm() < 1e-12, "{output}"); + } +} diff --git a/crates/cqlib-core/src/ir/qasm3/load.rs b/crates/cqlib-core/src/ir/qasm3/load.rs index 9c60592c..41448e5d 100644 --- a/crates/cqlib-core/src/ir/qasm3/load.rs +++ b/crates/cqlib-core/src/ir/qasm3/load.rs @@ -147,6 +147,41 @@ fn frontend_panic_error(payload: Box) -> Qasm3ParseErr Qasm3ParseError::ParseError(format!("OpenQASM 3 front-end failed: {message}")) } +fn reject_end_statements(stmts: &[Stmt]) -> Result<(), Qasm3ParseError> { + // Check every scope before constant folding or loop expansion can discard + // statements. The circuit IR cannot preserve whole-program termination. + let mut pending = vec![stmts]; + while let Some(stmts) = pending.pop() { + for stmt in stmts { + match stmt { + Stmt::End => return Err(Qasm3ParseError::UnsupportedFeature("end".to_string())), + Stmt::Block(block) => pending.push(block.statements()), + Stmt::If(op) => { + pending.push(op.then_branch().statements()); + if let Some(block) = op.else_branch() { + pending.push(block.statements()); + } + } + Stmt::While(op) => pending.push(op.loop_body().statements()), + Stmt::ForStmt(op) => pending.push(op.loop_body().statements()), + Stmt::SwitchCaseStmt(op) => { + for case in op.cases() { + pending.push(case.statements()); + } + if let Some(stmts) = op.default_block() { + pending.push(stmts); + } + } + Stmt::GateDefinition(def) => pending.push(def.block().statements()), + Stmt::DefStmt(def) => pending.push(def.block().statements()), + Stmt::AnnotatedStmt(op) => pending.push(std::slice::from_ref(op.statement())), + _ => {} + } + } + } + Ok(()) +} + fn prepare_source(source: &str) -> Result { let layout = inspect_source(source)?; reject_empty_pragmas(&layout.code_mask)?; @@ -729,6 +764,7 @@ impl<'a> LoweringContext<'a> { ))); } + reject_end_statements(program.stmts())?; let total_qubits = self.discover_quantum(program.stmts())?; self.discover_gates(program.stmts())?; @@ -926,7 +962,8 @@ impl<'a> LoweringContext<'a> { "hardware qubit".to_string(), )), Stmt::Box => Err(Qasm3ParseError::UnsupportedFeature("box".to_string())), - Stmt::End | Stmt::NullStmt => Ok(()), + Stmt::End => Err(Qasm3ParseError::UnsupportedFeature("end".to_string())), + Stmt::NullStmt => Ok(()), Stmt::OldStyleDeclaration => Err(Qasm3ParseError::UnsupportedFeature( "old-style declaration".to_string(), )), diff --git a/crates/cqlib-core/src/ir/qasm3/load_test.rs b/crates/cqlib-core/src/ir/qasm3/load_test.rs index 9a9db6ef..b1ce4891 100644 --- a/crates/cqlib-core/src/ir/qasm3/load_test.rs +++ b/crates/cqlib-core/src/ir/qasm3/load_test.rs @@ -637,6 +637,120 @@ fn rejects_out_of_bounds_qubit_index() { ); } +#[test] +fn rejects_end_in_top_level_and_nested_scopes() { + for body in [ + "end;", + "x q; end; x q;", + "x q; end;", + "{ x q; end; } x q;", + "if (true) { x q; end; } x q;", + "bool flag = true; if (flag) { x q; end; } x q;", + "bool flag = false; if (flag) { x q; } else { end; } x q;", + "for uint i in [0:2] { x q; end; } x q;", + "while (true) { x q; end; } x q;", + "for uint i in [0:2] { if (true) { end; } } x q;", + "def stop() { end; } x q;", + "uint[2] c = 0; switch (c) { case 0 { end; } default { x q; } }", + "uint[2] c = 1; switch (c) { case 0 { x q; } default { end; } }", + ] { + let source = format!("OPENQASM 3.0; include \"stdgates.inc\"; qubit q; {body}"); + for loader in [loads, from_str] { + let result = loader(&source); + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection for {body:?}, got {result:?}" + ); + } + } +} + +#[test] +fn rejects_end_before_discarding_unreachable_statements() { + for body in [ + "if (false) { end; } x q;", + "if (true) { x q; } else { end; }", + "for uint i in [1:0] { end; } x q;", + "while (false) { end; } x q;", + "if (false) { for uint i in [1:0] { end; } } x q;", + ] { + let source = format!("OPENQASM 3.0; include \"stdgates.inc\"; qubit q; {body}"); + let result = loads(&source); + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection for {body:?}, got {result:?}" + ); + } +} + +#[test] +fn rejects_end_from_file() { + let path = unique_temp_path("end"); + fs::write( + &path, + "OPENQASM 3.0; include \"stdgates.inc\"; qubit q; x q; end; x q;", + ) + .unwrap(); + let loaded = load(&path); + let aliased = from_path(&path); + fs::remove_file(&path).unwrap(); + + for result in [loaded, aliased] { + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection, got {result:?}" + ); + } +} + +#[test] +fn rejects_end_from_included_file() { + let path = unique_temp_path("end_include"); + let included = path.with_extension("end"); + fs::write(&included, "if (false) { end; }").unwrap(); + fs::write( + &path, + format!( + "OPENQASM 3.0; include \"{}\";", + included.file_name().unwrap().to_str().unwrap() + ), + ) + .unwrap(); + let result = load(&path); + // An include path containing the keyword and comments are not statements. + fs::write(&included, "// end;\n/* end; */").unwrap(); + let without_end = load(&path); + fs::remove_file(&path).unwrap(); + fs::remove_file(&included).unwrap(); + + assert!( + matches!(&result, Err(Qasm3ParseError::UnsupportedFeature(feature)) if feature == "end"), + "expected explicit end rejection in include, got {result:?}" + ); + assert_eq!(without_end.unwrap().operations().len(), 0); +} + +#[test] +fn loads_null_statements_and_end_in_comments_and_identifiers() { + let circuit = loads( + r#" + OPENQASM 3.0; + include "stdgates.inc"; + qubit end_marker; + // end; + x end_marker; + /* if (true) { end; } */ + ; + h end_marker; + "#, + ) + .unwrap(); + + assert_eq!(circuit.operations().len(), 2); + assert_standard_gate(&circuit, 0, StandardGate::X, &[0]); + assert_standard_gate(&circuit, 1, StandardGate::H, &[0]); +} + #[test] fn rejects_unsupported_standard_gate() { assert_err( diff --git a/crates/cqlib-core/src/qis/entropy.rs b/crates/cqlib-core/src/qis/entropy.rs index 60b23f31..ec0791e1 100644 --- a/crates/cqlib-core/src/qis/entropy.rs +++ b/crates/cqlib-core/src/qis/entropy.rs @@ -92,12 +92,14 @@ pub fn linear_entropy(dm: &DensityMatrix) -> Result { /// # Arguments /// /// * `dm` - The density matrix representing the quantum state. -/// * `alpha` - The order parameter. Must be positive and not equal to 1.0 -/// (use Von Neumann entropy directly for α = 1). +/// * `alpha` - Positive order parameter, including 1.0 and positive infinity. +/// NaN is rejected. At α = 1 this returns the Von Neumann entropy; +/// positive infinity returns the min-entropy. /// /// # Returns /// -/// The Rényi entropy in bits (base-2 logarithm), or an error if α ≤ 0. +/// The Rényi entropy in bits (base-2 logarithm), or an error if α ≤ 0, +/// α is NaN, eigendecomposition fails, or no positive spectrum remains. /// /// # Examples /// @@ -115,8 +117,13 @@ pub fn linear_entropy(dm: &DensityMatrix) -> Result { /// /// For α very close to 1.0 (within `f64::EPSILON`), this function automatically /// falls back to computing the Von Neumann entropy for numerical stability. +/// Nearby orders use `expm1` and `log1p` to avoid cancellation. For non-diagonal +/// matrices, eigenvalues at or below `dimension * f64::EPSILON * max_eigenvalue` +/// are treated as numerical zeros. True eigenvalues below this resolution +/// cannot reliably be distinguished from eigensolver roundoff. Diagonal +/// matrices retain all positive entries without this cutoff. pub fn renyi_entropy(dm: &DensityMatrix, alpha: f64) -> Result { - if alpha <= 0.0 { + if alpha.is_nan() || alpha <= 0.0 { return Err(QisError::InvalidParameterValue( "Rényi entropy order alpha must be positive".to_string(), )); @@ -128,20 +135,57 @@ pub fn renyi_entropy(dm: &DensityMatrix, alpha: f64) -> Result { } let mat = super::metrics::density_matrix_to_faer(dm); - let eigenvalues: Vec = mat.self_adjoint_eigenvalues(Side::Lower).map_err(|e| { - QisError::UnsupportedOperation(format!("Eigendecomposition failed: {:?}", e)) - })?; - - // Compute sum of eigenvalues^alpha, handling numerical noise - let mut sum_power = 0.0; - for &eigval in &eigenvalues { - if eigval > 1e-12 { - sum_power += eigval.powf(alpha); - } + // A diagonal spectrum is already available exactly. Eigensolvers can lose + // relative accuracy in tiny eigenvalues, which matter at small alpha. + let diagonal = (0..mat.nrows()) + .all(|i| (0..mat.ncols()).all(|j| i == j || mat[(i, j)] == faer::c64::new(0.0, 0.0))); + let eigenvalues: Vec = if diagonal { + (0..mat.nrows()).map(|i| mat[(i, i)].re).collect() + } else { + mat.self_adjoint_eigenvalues(Side::Lower).map_err(|e| { + QisError::UnsupportedOperation(format!("Eigendecomposition failed: {:?}", e)) + })? + }; + + let max_eigenvalue = eigenvalues.iter().copied().fold(0.0, f64::max); + if !max_eigenvalue.is_finite() || max_eigenvalue == 0.0 { + return Err(QisError::NotNormalized); } - - // Rényi entropy formula: 1/(1-α) * log2(sum(λ_i^α)) - let entropy = sum_power.log2() / (1.0 - alpha); + // Small alpha amplifies positive roundoff in the null space of low-rank + // states. Scale the cutoff with eigensolver precision instead of using a + // fixed probability threshold, while keeping exact diagonal spectra. + let cutoff = if diagonal { + 0.0 + } else { + mat.nrows() as f64 * f64::EPSILON * max_eigenvalue + }; + let eigenvalues: Vec = eigenvalues.into_iter().filter(|&v| v > cutoff).collect(); + if alpha == f64::INFINITY { + return Ok((-max_eigenvalue.log2()).max(0.0)); + } + let delta = alpha - 1.0; + let entropy = if delta.abs() < 1e-5 { + // expm1/log1p avoid cancellation near alpha=1. Normalize the spectral + // weights here so trace roundoff is not amplified by division by delta. + let trace: f64 = eigenvalues.iter().sum(); + let change: f64 = eigenvalues + .iter() + .map(|&v| { + let p = v / trace; + p * (delta * p.ln()).exp_m1() + }) + .sum(); + -change.ln_1p() / delta / std::f64::consts::LN_2 + } else { + let max_log = max_eigenvalue.ln(); + let scaled_sum: f64 = eigenvalues + .iter() + .map(|v| (alpha * (v.ln() - max_log)).exp()) + .sum(); + // Divide before multiplying to avoid overflow even for alpha=f64::MAX. + ((alpha / (1.0 - alpha)) * max_log + scaled_sum.ln() / (1.0 - alpha)) + / std::f64::consts::LN_2 + }; Ok(entropy.max(0.0)) } @@ -442,10 +486,14 @@ pub fn concurrence(dm: &DensityMatrix) -> Result { /// This measure represents the minimum number of Bell pairs required to asymptotically /// create the state ρ using LOCC (Local Operations and Classical Communication). pub fn entanglement_of_formation(dm: &DensityMatrix) -> Result { - let c = concurrence(dm)?; + Ok(entanglement_of_formation_from_concurrence(concurrence(dm)?)) +} + +fn entanglement_of_formation_from_concurrence(c: f64) -> f64 { + let c = c.clamp(0.0, 1.0); if c < 1e-15 { - return Ok(0.0); + return 0.0; } // Compute x = (1 + sqrt(1 - C^2)) / 2 @@ -462,7 +510,7 @@ pub fn entanglement_of_formation(dm: &DensityMatrix) -> Result { binary_entropy -= (1.0 - x) * (1.0 - x).log2(); } - Ok(binary_entropy) + binary_entropy } /// Helper function to compute the matrix square root of a positive semi-definite matrix. diff --git a/crates/cqlib-core/src/qis/entropy_test.rs b/crates/cqlib-core/src/qis/entropy_test.rs index e0cf1ef4..d6d1be9c 100644 --- a/crates/cqlib-core/src/qis/entropy_test.rs +++ b/crates/cqlib-core/src/qis/entropy_test.rs @@ -666,6 +666,21 @@ fn test_eof_bell_states() { ); } +#[test] +fn test_eof_clamps_concurrence_roundoff_before_square_root() { + for c in [1.0, 1.0 + f64::EPSILON, 1.0 + 8.0 * f64::EPSILON] { + let eof = super::entanglement_of_formation_from_concurrence(c); + assert_eq!(eof, 1.0, "concurrence={c}, entropy={eof}"); + } + for c in [0.0, -f64::EPSILON] { + assert_eq!(super::entanglement_of_formation_from_concurrence(c), 0.0); + } + // An interior value still uses the binary entropy formula: C=0.6 gives x=0.9. + let expected = -0.9_f64 * 0.9_f64.log2() - 0.1_f64 * 0.1_f64.log2(); + let actual = super::entanglement_of_formation_from_concurrence(0.6); + assert!((actual - expected).abs() < 1e-14); +} + #[test] fn test_eof_separable_states() { // Separable states have EOF = 0 @@ -746,3 +761,105 @@ fn test_eof_concurrence_relationship() { assert!(c_sep.abs() < EPSILON); assert!(eof_sep.abs() < EPSILON); } + +#[test] +fn formation_entropy_of_rotated_maximally_entangled_state() { + let state = vec![ + Complex64::new(-0.5917562523120286, -0.14345273890626087), + Complex64::new(0.12739228627789673, 0.3361800930257551), + Complex64::new(-0.06600502193827436, 0.35339664207352467), + Complex64::new(-0.5571108451004554, 0.2457267928442915), + ]; + let dm = DensityMatrix::from_state(2, state).unwrap(); + let eof = entanglement_of_formation(&dm).unwrap(); + assert!( + eof.is_finite() && (0.0..=1.0).contains(&eof), + "entropy={eof}" + ); + // Square roots amplify O(epsilon) noise in zero eigenvalues to O(sqrt(epsilon)). + // Eigensolver backends differ in the sign of this noise on rank-one states. + let tolerance = 8.0 * f64::EPSILON.sqrt(); + assert!( + (eof - 1.0).abs() < tolerance, + "entropy={eof}, tolerance={tolerance}" + ); +} + +#[test] +fn renyi_extreme_orders_and_small_positive_eigenvalues() { + for n in 1..=3 { + let dm = DensityMatrix::maximally_mixed(n); + for alpha in [ + 0.1, + 1.0 - 1e-12, + 1.0, + 1.0 + 1e-12, + 2000.0, + f64::MAX, + f64::INFINITY, + ] { + assert!( + (renyi_entropy(&dm, alpha).unwrap() - n as f64).abs() < 1e-10, + "n={n}, alpha={alpha}" + ); + assert!(renyi_entropy(&DensityMatrix::new(n), alpha).unwrap().abs() < 1e-10); + } + } + let dm = DensityMatrix::from_density_matrix_state( + 1, + vec![(1.0 - 1e-14).into(), 0.0.into(), 0.0.into(), 1e-14.into()], + ) + .unwrap(); + assert!( + (renyi_entropy(&dm, 0.1).unwrap() - 0.06257881098503021).abs() < 1e-12, + "got {}", + renyi_entropy(&dm, 0.1).unwrap() + ); + assert!(renyi_entropy(&dm, f64::NAN).is_err()); +} + +#[test] +fn renyi_entropy_of_nondiagonal_pure_state_is_zero() { + let state = [1.0, 2.0, 3.0, 4.0] + .map(|v| Complex64::new(v / 30.0_f64.sqrt(), 0.0)) + .to_vec(); + let dm = DensityMatrix::from_state(2, state).unwrap(); + for alpha in [0.01, 0.1, 0.5, 1.0, 2.0, f64::INFINITY] { + let actual = renyi_entropy(&dm, alpha).unwrap(); + assert!(actual.abs() < 1e-10, "alpha={alpha}, entropy={actual}"); + } +} + +#[test] +fn renyi_entropy_preserves_rank_deficient_spectrum_under_unitary_rotation() { + // The first two columns of the four-dimensional Fourier matrix are + // orthonormal, so this state has spectrum [0.8, 0.2, 0, 0]. + let column = [ + Complex64::new(1.0, 0.0), + Complex64::new(0.0, 1.0), + Complex64::new(-1.0, 0.0), + Complex64::new(0.0, -1.0), + ]; + let mut rho = Vec::new(); + let mut diagonal = vec![Complex64::new(0.0, 0.0); 16]; + diagonal[0] = 0.8.into(); + diagonal[5] = 0.2.into(); + for i in 0..4 { + for j in 0..4 { + rho.push((Complex64::new(0.8, 0.0) + 0.2 * column[i] * column[j].conj()) / 4.0); + } + } + for data in [diagonal, rho] { + let dm = DensityMatrix::from_density_matrix_state(2, data).unwrap(); + for alpha in [0.01, 0.1, 0.5, 1.0, 2.0, f64::INFINITY] { + let expected = if alpha == 1.0 { + -0.8_f64 * 0.8_f64.log2() - 0.2_f64 * 0.2_f64.log2() + } else if alpha == f64::INFINITY { + -0.8_f64.log2() + } else { + (0.8_f64.powf(alpha) + 0.2_f64.powf(alpha)).log2() / (1.0 - alpha) + }; + assert!((renyi_entropy(&dm, alpha).unwrap() - expected).abs() < 1e-10); + } + } +} diff --git a/crates/cqlib-core/src/qis/error.rs b/crates/cqlib-core/src/qis/error.rs index 808e764c..6cbf3aff 100644 --- a/crates/cqlib-core/src/qis/error.rs +++ b/crates/cqlib-core/src/qis/error.rs @@ -11,6 +11,7 @@ // that they have been altered from the originals. use crate::circuit::CircuitError; +use num_complex::Complex64; use thiserror::Error; /// Comprehensive error type for the `qis` (Quantum Information Science) module. @@ -19,6 +20,21 @@ use thiserror::Error; /// density matrix simulation, observables, Hamiltonians, and Pauli operator manipulations. #[derive(Debug, Error)] pub enum QisError { + /// A fermionic mode lies outside the declared mode space. + #[error("Fermionic mode {mode} is out of bounds for {num_modes} modes")] + ModeOutOfBounds { mode: usize, num_modes: usize }, + + /// Fermionic operators must declare the same mode count. + #[error("Mode count mismatch: expected {expected}, got {actual}")] + ModeMismatch { expected: usize, actual: usize }, + + /// Operator coefficients and arithmetic results must be finite. + #[error("Operator coefficient must be finite, got {coefficient}")] + NonFiniteCoefficient { coefficient: Complex64 }, + + /// A fermionic occupation must be either zero or one. + #[error("Invalid occupation at mode {index}: expected 0 or 1, got {value}")] + InvalidOccupation { index: usize, value: u8 }, /// Errors originating from quantum circuit operations, such as unsupported gates /// or symbolic parameters. #[error(transparent)] @@ -90,6 +106,14 @@ pub enum QisError { NonCliffordGate(String), } +pub(crate) fn validate_coefficient(coefficient: Complex64) -> Result<(), QisError> { + if coefficient.re.is_finite() && coefficient.im.is_finite() { + Ok(()) + } else { + Err(QisError::NonFiniteCoefficient { coefficient }) + } +} + /// Error type for parsing PauliString from a string representation. #[derive(Debug, Clone, PartialEq, Eq, Error)] pub enum PauliStringParseError { diff --git a/crates/cqlib-core/src/qis/evolution.rs b/crates/cqlib-core/src/qis/evolution.rs index 2079e981..dc4bde31 100644 --- a/crates/cqlib-core/src/qis/evolution.rs +++ b/crates/cqlib-core/src/qis/evolution.rs @@ -449,6 +449,16 @@ pub(crate) fn trotter_second_order_core( Ok(()) } +// Numeric evolution historically reports coefficient overflow as unsupported. +fn normalized_evolution(h: &Hamiltonian) -> Result { + h.normalized_hermitian().map_err(|error| match error { + nonfinite @ QisError::NonFiniteCoefficient { .. } => { + QisError::UnsupportedOperation(nonfinite.to_string()) + } + other => other, + }) +} + impl Hamiltonian { /// Converts the Hamiltonian to a Trotterized time evolution circuit. /// @@ -459,6 +469,8 @@ impl Hamiltonian { /// the Hamiltonian terms commute. For an auto-selecting method that uses the /// mathematically exact single-pass decomposition when all terms commute, see /// [`to_evolution_circuit`](Hamiltonian::to_evolution_circuit). + /// Nonempty sums that cancel to zero produce an identity circuit, retaining + /// the declared qubit count. An empty input sum is rejected. /// /// # Arguments /// @@ -521,15 +533,7 @@ impl Hamiltonian { )); } - let mut simplified_h = self.clone(); - simplified_h.simplify(); - - for (_, coeff) in &simplified_h.terms { - if coeff.im.abs() > 1e-10 { - return Err(QisError::NotHermitian); - } - } - + let simplified_h = normalized_evolution(self)?; let mut circuit = Circuit::new(simplified_h.num_qubits); let qubits: Vec = circuit.qubits(); let t = ParameterValue::Fixed(time); @@ -591,6 +595,8 @@ impl Hamiltonian { /// This mirrors the behavior of [`PauliEvolutionAnsatz`] with /// [`EvolutionStrategy::Auto`], closing the capability gap between the numeric /// and parametric APIs. + /// Nonempty sums that cancel to zero produce an identity circuit, retaining + /// the declared qubit count. An empty input sum is rejected. /// /// # Arguments /// @@ -641,15 +647,7 @@ impl Hamiltonian { )); } - let mut simplified_h = self.clone(); - simplified_h.simplify(); - - for (_, coeff) in &simplified_h.terms { - if coeff.im.abs() > 1e-10 { - return Err(QisError::NotHermitian); - } - } - + let simplified_h = normalized_evolution(self)?; let mut circuit = Circuit::new(simplified_h.num_qubits); let qubits: Vec = circuit.qubits(); diff --git a/crates/cqlib-core/src/qis/evolution_test.rs b/crates/cqlib-core/src/qis/evolution_test.rs index 31312e9b..9ace77e2 100644 --- a/crates/cqlib-core/src/qis/evolution_test.rs +++ b/crates/cqlib-core/src/qis/evolution_test.rs @@ -732,3 +732,27 @@ fn test_evolution_circuit_exact_matrix_correctness() { assert_abs_diff_eq!(matrix[[0, 1]].re, 0.0, epsilon = 1e-12); assert_abs_diff_eq!(matrix[[1, 0]].re, 0.0, epsilon = 1e-12); } + +#[test] +fn evolution_retains_small_coefficients_before_time_scaling() { + for coefficients in [vec![1e-11], vec![2e-11, -1e-11], vec![1e-11, -1e-11]] { + let mut h = Hamiltonian::new(1); + for &c in &coefficients { + h.add_term("Z".parse().unwrap(), c.into()).unwrap(); + } + let angle = coefficients.iter().sum::() * 1e11; + for mode in [TrotterMode::FirstOrder, TrotterMode::SecondOrder] { + for circuit in [ + h.to_trotter_circuit(1e11, 3, mode).unwrap(), + h.to_evolution_circuit(1e11, 3, mode).unwrap(), + ] { + let m = circuit_to_matrix(&circuit, None).unwrap(); + assert!((m[[0, 0]] - Complex64::from_polar(1.0, -angle)).norm() < 1e-10); + assert!((m[[1, 1]] - Complex64::from_polar(1.0, angle)).norm() < 1e-10); + assert!(m[[0, 1]].norm() < 1e-10 && m[[1, 0]].norm() < 1e-10); + } + } + h.simplify(); + assert!(h.terms.is_empty()); + } +} diff --git a/crates/cqlib-core/src/qis/fermion/mapping/jordan_wigner.rs b/crates/cqlib-core/src/qis/fermion/mapping/jordan_wigner.rs new file mode 100644 index 00000000..db60aaf9 --- /dev/null +++ b/crates/cqlib-core/src/qis/fermion/mapping/jordan_wigner.rs @@ -0,0 +1,106 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Jordan–Wigner mapping using sparse Pauli arithmetic. + +use super::{FermionToQubitMapper, OccupationStateMapper}; +use crate::qis::fermion::{FermionicLadder, FermionicOp}; +use crate::qis::{Hamiltonian, Pauli, PauliString, QisError}; +use num_complex::Complex64; +use std::collections::BTreeMap; + +/// Jordan–Wigner encoding with mode p mapped to qubit p. +/// +/// The Z chain covers modes `0..p`: creation is `Z_chain (X_p - iY_p)/2`, +/// annihilation is `Z_chain (X_p + iY_p)/2`. Qubit zero is the least-significant +/// basis bit, and the rightmost character of a displayed Pauli string. +/// Mapping never constructs a dense matrix or implicitly normal orders its input. +/// A product of k ladders can expand to 2^k terms before sparse merging. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct JordanWignerMapper; + +impl JordanWignerMapper { + /// Creates a stateless mapper. + pub fn new() -> Self { + Self + } +} + +impl FermionToQubitMapper for JordanWignerMapper { + fn num_qubits(&self, num_modes: usize) -> usize { + num_modes + } + + fn map_operator(&self, op: &FermionicOp) -> Result { + let n = self.num_qubits(op.num_modes()); + let mut result = Hamiltonian::new(n); + // Build only the components needed by this input, and reuse them across terms. + let mut components = BTreeMap::new(); + for (term, coefficient) in op.terms() { + let mut product = Hamiltonian::new(n); + // Merge the unit-weight product before applying the input coefficient, + // so representable small results are not lost in ladder intermediates. + product.add_term(PauliString::new(n), Complex64::new(1.0, 0.0))?; + for ladder in term { + let p = ladder.mode(); + let (x, y) = components.entry(p).or_insert_with(|| { + let mut x = PauliString::new(n); + let mut y = PauliString::new(n); + for j in 0..p { + x.set_pauli(j, Pauli::Z); + y.set_pauli(j, Pauli::Z); + } + x.set_pauli(p, Pauli::X); + y.set_pauli(p, Pauli::Y); + (x, y) + }); + let imaginary = match ladder { + FermionicLadder::Create(_) => -0.5, + FermionicLadder::Annihilate(_) => 0.5, + }; + let mut next = Hamiltonian::new(n); + for (pauli, c) in &product.terms { + next.add_term(pauli * &*x, *c * 0.5)?; + next.add_term(pauli * &*y, *c * Complex64::new(0.0, imaginary))?; + } + product = next.normalized()?; + if product.terms.is_empty() { + break; + } + } + result.terms.extend( + product + .terms + .into_iter() + .map(|(pauli, c)| (pauli, c * coefficient)), + ); + } + result.normalized() + } +} + +impl OccupationStateMapper for JordanWignerMapper { + fn map_occupation(&self, occupation: &[u8]) -> Result, QisError> { + occupation + .iter() + .enumerate() + .map(|(index, value)| match value { + 0 => Ok(false), + 1 => Ok(true), + value => Err(QisError::InvalidOccupation { + index, + value: *value, + }), + }) + .collect() + } +} diff --git a/crates/cqlib-core/src/qis/fermion/mapping/mod.rs b/crates/cqlib-core/src/qis/fermion/mapping/mod.rs new file mode 100644 index 00000000..b7fed5dd --- /dev/null +++ b/crates/cqlib-core/src/qis/fermion/mapping/mod.rs @@ -0,0 +1,37 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Contracts for fermion-to-qubit operators and occupation-state encodings. + +pub mod jordan_wigner; +pub use jordan_wigner::JordanWignerMapper; + +use super::FermionicOp; +use crate::qis::{Hamiltonian, QisError}; + +/// Maps finite fermionic operators, including non-Hermitian operators, to Pauli sums. +/// Circuit synthesis and Hermiticity requirements belong to downstream consumers. +pub trait FermionToQubitMapper { + /// Maps an operator while preserving its declared mode space. + fn map_operator(&self, op: &FermionicOp) -> Result; + /// Returns the qubit count required to encode the given mode space. + fn num_qubits(&self, num_modes: usize) -> usize; +} + +/// Encodes occupations into computational-basis bits, where `bits[p]` addresses qp. +/// This is separate from operator mapping because some encodings do not map +/// occupations to individual computational basis states. +pub trait OccupationStateMapper { + /// Maps a vector of zero/one occupations; its length defines the mode count. + /// An empty vector encodes the zero-mode vacuum as an empty bit vector. + fn map_occupation(&self, occupation: &[u8]) -> Result, QisError>; +} diff --git a/crates/cqlib-core/src/qis/fermion/mod.rs b/crates/cqlib-core/src/qis/fermion/mod.rs new file mode 100644 index 00000000..324fcdbe --- /dev/null +++ b/crates/cqlib-core/src/qis/fermion/mod.rs @@ -0,0 +1,74 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Fermionic algebra, qubit mappings and occupation encodings. +//! +//! Modes are numbered from zero. Ordered products act right-to-left. The Fock +//! basis is `|n_{N-1} ... n_0> = (a†_0)^n_0 ... (a†_{N-1})^n_{N-1} |vac>`. +//! Qubit zero is the least-significant bit; state indices are `sum(n_p * 2^p)`. +//! Core does not assign spin or chemical-orbital meanings to these indices. +//! Zero and identity operators retain their declared mode count, including zero +//! modes. Circuit consumers can have stricter requirements: basis encoding needs +//! nonempty bits, and `PauliEvolutionAnsatz` needs a nonzero Hermitian operator. +//! Numeric evolution rejects empty input sums but returns identity evolution +//! when a nonempty sum cancels to zero. +//! +//! # Particle-number observable +//! ``` +//! use cqlib_core::qis::{FermionicOp, FermionToQubitMapper, JordanWignerMapper, +//! Observable, Statevector}; +//! let mapper = JordanWignerMapper::new(); +//! let number = mapper.map_operator(&FermionicOp::total_number(3))?; +//! let mut state = Statevector::new(3); +//! state.apply_x(0); +//! state.apply_x(2); +//! assert_eq!(number.expectation_statevector(&state)?, 2.0); +//! # Ok::<(), cqlib_core::qis::QisError>(()) +//! ``` +//! +//! # Parameterized excitation evolution +//! ``` +//! use cqlib_core::qis::{FermionicOp, +//! FermionToQubitMapper, JordanWignerMapper}; +//! use cqlib_core::circuit::ansatz::{Ansatz, PauliEvolutionAnsatz}; +//! let h = FermionicOp::excitation_generator(4, &[0, 1], &[2, 3])?; +//! // e^(-i H theta) = e^(theta (T - T†)). +//! let mapped = JordanWignerMapper::new().map_operator(&h)?; +//! let circuit = PauliEvolutionAnsatz::new(mapped)?.build_circuit("excitation")?; +//! assert_eq!(circuit.num_qubits(), 4); +//! # Ok::<(), cqlib_core::qis::QisError>(()) +//! ``` +//! +//! Each excitation can have an independent parameter: build one evolution +//! block per generator with a distinct `with_time_param_name`, then append +//! the blocks using [`crate::circuit::Circuit::compose`]. A single ansatz built +//! from a sum of generators instead has one shared time parameter. +//! +//! # Occupation-state encoding +//! ``` +//! use cqlib_core::qis::{JordanWignerMapper, OccupationStateMapper, Statevector}; +//! use cqlib_core::circuit::ansatz::{Ansatz, BasisEncoding}; +//! let bits = JordanWignerMapper::new().map_occupation(&[1, 0, 0])?; +//! let circuit = BasisEncoding::new(bits).build_circuit("reference")?; +//! let state = Statevector::from_circuit(&circuit)?; +//! assert_eq!(state.probabilities()[1], 1.0); // displayed as |001> +//! # Ok::<(), cqlib_core::qis::QisError>(()) +//! ``` + +pub mod mapping; +pub mod operator; + +pub use mapping::{FermionToQubitMapper, JordanWignerMapper, OccupationStateMapper}; +pub use operator::{FermionicLadder, FermionicOp}; + +#[cfg(test)] +mod tests; diff --git a/crates/cqlib-core/src/qis/fermion/operator.rs b/crates/cqlib-core/src/qis/fermion/operator.rs new file mode 100644 index 00000000..4b234d96 --- /dev/null +++ b/crates/cqlib-core/src/qis/fermion/operator.rs @@ -0,0 +1,516 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Structured fermionic operators and canonical anticommutation algebra. + +use crate::qis::QisError; +use crate::qis::error::validate_coefficient; +use num_complex::Complex64; +use std::collections::{BTreeMap, BTreeSet}; +use std::ops::{Add, Mul, Neg, Sub}; + +/// A creation or annihilation operator on a zero-based fermionic mode. +/// +/// A sequence `[A, B]` denotes the mathematical product `A B`: `B` acts first. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum FermionicLadder { + /// Creates a particle in the given mode. + Create(usize), + /// Removes a particle from the given mode. + Annihilate(usize), +} + +impl FermionicLadder { + /// Returns the mode on which this operator acts. + pub fn mode(self) -> usize { + match self { + Self::Create(mode) | Self::Annihilate(mode) => mode, + } + } + + /// Exchanges creation and annihilation. + pub fn adjoint(self) -> Self { + match self { + Self::Create(mode) => Self::Annihilate(mode), + Self::Annihilate(mode) => Self::Create(mode), + } + } +} + +/// A finite complex linear combination of ordered fermionic products. +/// +/// The declared mode count is retained even for zero and identity operators. +/// Equal ordered products are merged automatically; only exact zero coefficients +/// are removed. Products are not automatically normal ordered. Use [`Self::chop`] +/// for explicit numerical truncation and [`Self::equiv`] for algebraic equivalence. +/// Structural equality also compares the declared mode count. +/// +/// Fallible arithmetic operators return `Result`, for example `(&a + &b)?`. +#[derive(Debug, Clone, PartialEq)] +pub struct FermionicOp { + num_modes: usize, + terms: BTreeMap, Complex64>, +} + +pub(crate) fn validate_tolerance(atol: f64) -> Result<(), QisError> { + if !atol.is_finite() || atol < 0.0 { + return Err(QisError::InvalidParameterValue( + "tolerance must be finite and nonnegative".into(), + )); + } + Ok(()) +} + +impl FermionicOp { + /// Creates the zero operator on the declared mode space, including zero modes. + pub fn new(num_modes: usize) -> Self { + Self { + num_modes, + terms: BTreeMap::new(), + } + } + + /// Creates the identity. An empty product is the identity, not the zero operator. + pub fn identity(num_modes: usize) -> Self { + let mut result = Self::new(num_modes); + result.terms.insert(Vec::new(), Complex64::new(1.0, 0.0)); + result + } + + /// Creates a weighted ordered product. Even zero-weight terms are validated. + pub fn from_term( + num_modes: usize, + term: impl IntoIterator, + coefficient: Complex64, + ) -> Result { + let mut result = Self::new(num_modes); + result.add_term(term, coefficient)?; + Ok(result) + } + + /// Creates a sum of products, merging duplicates without numerical truncation. + pub fn from_terms( + num_modes: usize, + terms: impl IntoIterator, Complex64)>, + ) -> Result { + let mut result = Self::new(num_modes); + for (term, coefficient) in terms { + result.add_term(term, coefficient)?; + } + Ok(result) + } + + /// Adds a weighted product atomically; an error leaves this operator unchanged. + pub fn add_term( + &mut self, + term: impl IntoIterator, + coefficient: Complex64, + ) -> Result<(), QisError> { + validate_coefficient(coefficient)?; + let term: Vec<_> = term.into_iter().collect(); + for ladder in &term { + let mode = ladder.mode(); + if mode >= self.num_modes { + return Err(QisError::ModeOutOfBounds { + mode, + num_modes: self.num_modes, + }); + } + } + let merged = self.terms.get(&term).copied().unwrap_or_default() + coefficient; + validate_coefficient(merged)?; + if merged == Complex64::new(0.0, 0.0) { + self.terms.remove(&term); + } else { + self.terms.insert(term, merged); + } + Ok(()) + } + + /// Creates a single creation operator. + pub fn creation(num_modes: usize, mode: usize) -> Result { + Self::from_term(num_modes, [FermionicLadder::Create(mode)], 1.0.into()) + } + + /// Creates a single annihilation operator. + pub fn annihilation(num_modes: usize, mode: usize) -> Result { + Self::from_term(num_modes, [FermionicLadder::Annihilate(mode)], 1.0.into()) + } + + /// Creates the number operator `a†_p a_p`. + pub fn number(num_modes: usize, mode: usize) -> Result { + Self::from_term( + num_modes, + [ + FermionicLadder::Create(mode), + FermionicLadder::Annihilate(mode), + ], + 1.0.into(), + ) + } + + /// Creates the total particle-number operator, or zero for zero modes. + pub fn total_number(num_modes: usize) -> Self { + let terms = (0..num_modes) + .map(|mode| { + ( + vec![ + FermionicLadder::Create(mode), + FermionicLadder::Annihilate(mode), + ], + 1.0.into(), + ) + }) + .collect(); + Self { num_modes, terms } + } + + /// Creates the unit-weight Hermitian excitation generator `G = i(T - T†)`. + /// + /// For `sources = [i_0, ..., i_{r-1}]` and `targets = [a_0, ..., a_{r-1}]`, + /// the ordered excitation is + /// `T = a†_{a_0} ... a†_{a_{r-1}} a_{i_{r-1}} ... a_{i_0}`. + /// The rightmost operator acts first. Thus `[i, j] -> [a, b]` means + /// `T = a†_a a†_b a_j a_i`. + /// + /// Input order is preserved, without implicit sorting or normal ordering. + /// An odd permutation of either list negates `G`; applying odd permutations + /// to both lists preserves it. Explicit [`Self::normal_order`] preserves + /// these fermionic signs. No factorial or other normalization is applied. + /// + /// Mapping `G` and evolving it with [`crate::circuit::ansatz::PauliEvolutionAnsatz`] + /// implements `exp(-i θ G) = exp(θ (T - T†))`. The evolution parameter belongs + /// to the ansatz, not this operator. The generator conserves total particle + /// number. Reference occupations and spin interpretations are caller choices. + /// + /// # Errors + /// + /// Returns [`QisError::InvalidParameterValue`] if the lists are empty, have + /// unequal lengths, contain repeated modes, or overlap. Returns + /// [`QisError::ModeOutOfBounds`] if an index is outside `0..num_modes`. + /// + /// # Example + /// ``` + /// use cqlib_core::qis::FermionicOp; + /// let single = FermionicOp::excitation_generator(4, &[0], &[2])?; + /// let double = FermionicOp::excitation_generator(4, &[0, 1], &[2, 3])?; + /// assert!(single.is_hermitian(0.0)?); + /// assert!(double.is_hermitian(0.0)?); + /// # Ok::<(), cqlib_core::qis::QisError>(()) + /// ``` + pub fn excitation_generator( + num_modes: usize, + sources: &[usize], + targets: &[usize], + ) -> Result { + if sources.len() != targets.len() { + return Err(QisError::InvalidParameterValue( + "excitation sources and targets must have equal lengths".into(), + )); + } + if sources.is_empty() { + return Err(QisError::InvalidParameterValue( + "excitation sources and targets must be nonempty".into(), + )); + } + + let mut source_modes = BTreeSet::new(); + let mut target_modes = BTreeSet::new(); + for (label, modes, seen) in [ + ("sources", sources, &mut source_modes), + ("targets", targets, &mut target_modes), + ] { + for &mode in modes { + if mode >= num_modes { + return Err(QisError::ModeOutOfBounds { mode, num_modes }); + } + if !seen.insert(mode) { + return Err(QisError::InvalidParameterValue(format!( + "excitation {label} contain repeated mode {mode}" + ))); + } + } + } + if let Some(mode) = source_modes.intersection(&target_modes).next() { + return Err(QisError::InvalidParameterValue(format!( + "excitation sources and targets overlap at mode {mode}" + ))); + } + + let term = targets.iter().copied().map(FermionicLadder::Create).chain( + sources + .iter() + .rev() + .copied() + .map(FermionicLadder::Annihilate), + ); + let excitation = Self::from_term(num_modes, term, 1.0.into())?; + excitation + .try_sub(&excitation.adjoint())? + .scaled(Complex64::new(0.0, 1.0)) + } + + /// Returns the declared mode count. + pub fn num_modes(&self) -> usize { + self.num_modes + } + + /// Returns the number of stored ordered products. + pub fn num_terms(&self) -> usize { + self.terms.len() + } + + /// Iterates over products and their coefficients in deterministic structural order. + pub fn terms(&self) -> impl ExactSizeIterator + '_ { + self.terms + .iter() + .map(|(term, coefficient)| (term.as_slice(), *coefficient)) + } + + /// Reports whether the stored sum is zero. Algebraic cancellations require normal ordering. + pub fn is_zero(&self) -> bool { + self.terms.is_empty() + } + + fn check_modes(&self, other: &Self) -> Result<(), QisError> { + if self.num_modes != other.num_modes { + return Err(QisError::ModeMismatch { + expected: self.num_modes, + actual: other.num_modes, + }); + } + Ok(()) + } + + /// Adds operators on the same mode space, without modifying either operand. + pub fn try_add(&self, other: &Self) -> Result { + self.check_modes(other)?; + let mut result = self.clone(); + for (term, coefficient) in other.terms() { + result.add_term(term.iter().copied(), coefficient)?; + } + Ok(result) + } + + /// Subtracts operators on the same mode space. + pub fn try_sub(&self, other: &Self) -> Result { + self.check_modes(other)?; + let mut result = self.clone(); + for (term, coefficient) in other.terms() { + result.add_term(term.iter().copied(), -coefficient)?; + } + Ok(result) + } + + /// Forms `self * other`; the right operand acts first. Does not normal order. + pub fn try_mul(&self, other: &Self) -> Result { + self.check_modes(other)?; + let mut result = Self::new(self.num_modes); + for (left, a) in self.terms() { + for (right, b) in other.terms() { + result.add_term(left.iter().chain(right).copied(), a * b)?; + } + } + Ok(result) + } + + /// Scales all coefficients. The factor is validated even for the zero operator. + pub fn scaled(&self, factor: Complex64) -> Result { + validate_coefficient(factor)?; + Self::from_terms( + self.num_modes, + self.terms + .iter() + .map(|(term, c)| (term.clone(), *c * factor)), + ) + } + + /// Takes the conjugate transpose, reversing each product without reordering it. + pub fn adjoint(&self) -> Self { + Self { + num_modes: self.num_modes, + terms: self + .terms + .iter() + .map(|(term, coefficient)| { + ( + term.iter().rev().map(|ladder| ladder.adjoint()).collect(), + coefficient.conj(), + ) + }) + .collect(), + } + } + + /// Expands using the canonical anticommutation relations. + /// + /// Creators precede annihilators; each group uses ascending mode indices. + /// This is an equivalent operator expansion, including contraction terms: + /// `a_p a†_p = I - a†_p a_p`. Small nonzero coefficients are retained. + /// An explicit work stack avoids recursion in long products. + /// Sorting a branch of k ladders takes O(k²) comparisons; contractions can + /// produce additional branches. + pub fn normal_order(&self) -> Result { + let mut result = Self::new(self.num_modes); + let mut pending: Vec<_> = self + .terms + .iter() + .map(|(term, c)| (term.clone(), *c, 0usize)) + .collect(); + while let Some((mut term, mut coefficient, mut index)) = pending.pop() { + let mut complete = true; + while index + 1 < term.len() { + let left = term[index]; + let right = term[index + 1]; + if left == right { + complete = false; + break; + } + if left > right { + // Swapping distinct fermionic ladders contributes a minus sign. + // Equal-mode annihilator/creator pairs also contribute a contraction. + if let (FermionicLadder::Annihilate(p), FermionicLadder::Create(q)) = + (left, right) + && p == q + { + let mut contracted = term.clone(); + contracted.drain(index..index + 2); + // The prefix is already sorted. Removing this pair only + // requires rechecking the new boundary with that prefix. + pending.push((contracted, coefficient, index.saturating_sub(1))); + } + term.swap(index, index + 1); + coefficient = -coefficient; + // Revisit the changed boundary, rather than scanning from zero. + index = index.saturating_sub(1); + } else { + index += 1; + } + } + if complete { + result.add_term(term, coefficient)?; + } + } + Ok(result) + } + + /// Explicitly removes coefficients whose complex magnitude is at most `atol`. + /// Invalid tolerances leave the operator unchanged. + pub fn chop(&mut self, atol: f64) -> Result<(), QisError> { + validate_tolerance(atol)?; + self.terms + .retain(|_, coefficient| coefficient.norm() > atol); + Ok(()) + } + + /// Compares operators algebraically after normal ordering their difference. + /// Different mode counts are an error; `atol` must be finite and nonnegative. + pub fn equiv(&self, other: &Self, atol: f64) -> Result { + validate_tolerance(atol)?; + let difference = self.try_sub(other)?.normal_order()?; + Ok(difference + .terms + .values() + .all(|coefficient| coefficient.norm() <= atol)) + } + + /// Checks Hermiticity algebraically, allowing non-normal-ordered inputs. + pub fn is_hermitian(&self, atol: f64) -> Result { + self.equiv(&self.adjoint(), atol) + } +} + +macro_rules! binary_operator { + ($trait:ident, $method:ident, $checked:ident) => { + impl $trait<&FermionicOp> for &FermionicOp { + type Output = Result; + fn $method(self, rhs: &FermionicOp) -> Self::Output { + self.$checked(rhs) + } + } + impl $trait for FermionicOp { + type Output = Result; + fn $method(self, rhs: FermionicOp) -> Self::Output { + self.$checked(&rhs) + } + } + impl $trait<&FermionicOp> for FermionicOp { + type Output = Result; + fn $method(self, rhs: &FermionicOp) -> Self::Output { + self.$checked(rhs) + } + } + impl $trait for &FermionicOp { + type Output = Result; + fn $method(self, rhs: FermionicOp) -> Self::Output { + self.$checked(&rhs) + } + } + }; +} + +binary_operator!(Add, add, try_add); +binary_operator!(Sub, sub, try_sub); +binary_operator!(Mul, mul, try_mul); + +macro_rules! scalar_operator { + ($scalar:ty) => { + impl Mul<$scalar> for &FermionicOp { + type Output = Result; + fn mul(self, rhs: $scalar) -> Self::Output { + self.scaled(rhs.into()) + } + } + impl Mul<$scalar> for FermionicOp { + type Output = Result; + fn mul(self, rhs: $scalar) -> Self::Output { + self.scaled(rhs.into()) + } + } + impl Mul<&FermionicOp> for $scalar { + type Output = Result; + fn mul(self, rhs: &FermionicOp) -> Self::Output { + rhs.scaled(self.into()) + } + } + impl Mul for $scalar { + type Output = Result; + fn mul(self, rhs: FermionicOp) -> Self::Output { + rhs.scaled(self.into()) + } + } + }; +} + +scalar_operator!(f64); +scalar_operator!(Complex64); + +impl Neg for &FermionicOp { + type Output = FermionicOp; + fn neg(self) -> Self::Output { + let mut result = self.clone(); + for coefficient in result.terms.values_mut() { + *coefficient = -*coefficient; + } + result + } +} + +impl Neg for FermionicOp { + type Output = Self; + fn neg(mut self) -> Self::Output { + for coefficient in self.terms.values_mut() { + *coefficient = -*coefficient; + } + self + } +} diff --git a/crates/cqlib-core/src/qis/fermion/tests.rs b/crates/cqlib-core/src/qis/fermion/tests.rs new file mode 100644 index 00000000..5a90d144 --- /dev/null +++ b/crates/cqlib-core/src/qis/fermion/tests.rs @@ -0,0 +1,1119 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +use super::*; +use crate::circuit::ansatz::{Ansatz, BasisEncoding, EvolutionStrategy, PauliEvolutionAnsatz}; +use crate::circuit::circuit_to_matrix::circuit_to_matrix; +use crate::qis::{ + DensityMatrix, Hamiltonian, Observable, PauliString, Phase, QisError, Statevector, TrotterMode, +}; +use FermionicLadder::{Annihilate, Create}; +use ndarray::Array2; +use num_complex::Complex64; +use std::collections::{BTreeMap, HashMap}; + +// Independent Fock-basis action: no Pauli matrices or mapping formulas are used. +fn fock_matrix(op: &FermionicOp) -> Array2 { + let dim = 1 << op.num_modes(); + let mut matrix = Array2::zeros((dim, dim)); + for (word, coefficient) in op.terms() { + for source in 0..dim { + let mut state = source; + let mut amplitude = coefficient; + for ladder in word.iter().rev() { + let p = ladder.mode(); + let occupied = state & (1 << p) != 0; + if matches!(ladder, Create(_)) == occupied { + amplitude = Complex64::new(0.0, 0.0); + break; + } + if (state & ((1 << p) - 1)).count_ones() % 2 == 1 { + amplitude = -amplitude; + } + state ^= 1 << p; + } + matrix[[state, source]] += amplitude; + } + } + matrix +} + +fn assert_matrix_close(left: &Array2, right: &Array2) { + assert_eq!(left.dim(), right.dim()); + for (a, b) in left.iter().zip(right) { + assert!((*a - *b).norm() < 1e-11, "{a} != {b}"); + } +} + +// Independent occupation transitions for T: remove sources in input order, +// then insert targets in reverse order. This does not inspect FermionicOp words +// or use its algebra, normal ordering or JW mapping. +fn excitation_fock_matrix(n: usize, sources: &[usize], targets: &[usize]) -> Array2 { + let dim = 1usize << n; + let mut transition = Array2::::zeros((dim, dim)); + for initial in 0..dim { + let mut state = initial; + let mut sign = 1.0; + let mut allowed = true; + for (&mode, create) in sources + .iter() + .map(|p| (p, false)) + .chain(targets.iter().rev().map(|p| (p, true))) + { + if (state & (1 << mode) != 0) == create { + allowed = false; + break; + } + if (state & ((1 << mode) - 1)).count_ones() % 2 != 0 { + sign = -sign; + } + state ^= 1 << mode; + } + if allowed { + transition[[state, initial]] = Complex64::new(sign, 0.0); + } + } + (&transition - &transition.t().mapv(|c| c.conj())).mapv(|c| Complex64::new(0.0, 1.0) * c) +} + +#[test] +fn excitation_generator_validates_all_index_constraints() { + for (sources, targets) in [ + (vec![], vec![]), + (vec![], vec![1]), + (vec![0, 1], vec![2]), + (vec![0, 0], vec![2, 3]), + (vec![0, 1], vec![2, 2]), + (vec![0], vec![0]), + (vec![0, 1], vec![1, 2]), + ] { + assert!(matches!( + FermionicOp::excitation_generator(4, &sources, &targets), + Err(QisError::InvalidParameterValue(_)) + )); + } + for (n, sources, targets, invalid) in [ + (0, vec![0], vec![1], 0), + (4, vec![4], vec![1], 4), + (4, vec![0], vec![4], 4), + (4, vec![0], vec![usize::MAX], usize::MAX), + ] { + assert!(matches!( + FermionicOp::excitation_generator(n, &sources, &targets), + Err(QisError::ModeOutOfBounds { mode, num_modes }) + if mode == invalid && num_modes == n + )); + } +} + +#[test] +fn excitation_generator_preserves_input_order_and_permutation_signs() { + let g = FermionicOp::excitation_generator(5, &[1, 0], &[4, 2]).unwrap(); + let expected = FermionicOp::from_terms( + 5, + [ + ( + vec![Create(4), Create(2), Annihilate(0), Annihilate(1)], + Complex64::new(0.0, 1.0), + ), + ( + vec![Create(1), Create(0), Annihilate(2), Annihilate(4)], + Complex64::new(0.0, -1.0), + ), + ], + ) + .unwrap(); + assert_eq!(g, expected); + assert_eq!(g.num_modes(), 5); + assert_eq!(g.num_terms(), 2); + assert_eq!(g.adjoint(), g); + let ordered = g.normal_order().unwrap(); + assert_eq!( + FermionicOp::excitation_generator(5, &[0, 1], &[4, 2]) + .unwrap() + .normal_order() + .unwrap(), + -&ordered + ); + assert_eq!( + FermionicOp::excitation_generator(5, &[1, 0], &[2, 4]) + .unwrap() + .normal_order() + .unwrap(), + -&ordered + ); + assert_eq!( + FermionicOp::excitation_generator(5, &[0, 1], &[2, 4]) + .unwrap() + .normal_order() + .unwrap(), + ordered + ); + assert_eq!( + FermionicOp::excitation_generator(5, &[4, 2], &[1, 0]).unwrap(), + -&g + ); + + let triple = FermionicOp::excitation_generator(6, &[2, 0, 1], &[4, 5, 3]).unwrap(); + assert_matrix_close( + &fock_matrix(&triple), + &excitation_fock_matrix(6, &[2, 0, 1], &[4, 5, 3]), + ); +} + +#[test] +fn excitation_generator_single_and_double_have_expected_fock_signs() { + let single = FermionicOp::excitation_generator(3, &[0], &[2]).unwrap(); + let mut expected = Array2::::zeros((8, 8)); + let i = Complex64::new(0.0, 1.0); + expected[[4, 1]] = i; + expected[[1, 4]] = -i; + // A spectator in mode 1 flips the single-excitation sign. + expected[[6, 3]] = -i; + expected[[3, 6]] = i; + assert_eq!(fock_matrix(&single), expected); + + let double = FermionicOp::excitation_generator(4, &[0, 1], &[2, 3]).unwrap(); + let mut expected = Array2::::zeros((16, 16)); + expected[[12, 3]] = i; + expected[[3, 12]] = -i; + assert_eq!(fock_matrix(&double), expected); +} + +#[test] +fn excitation_generators_match_fock_action_and_conserve_particle_number() { + let mapper = JordanWignerMapper::new(); + let check = |n, sources: &[usize], targets: &[usize]| { + let op = FermionicOp::excitation_generator(n, sources, targets).unwrap(); + let expected = excitation_fock_matrix(n, sources, targets); + assert_eq!(fock_matrix(&op), expected); + assert_eq!(expected, expected.t().mapv(|c| c.conj())); + assert!(op.is_hermitian(0.0).unwrap()); + assert_eq!(fock_matrix(&op.normal_order().unwrap()), expected); + assert_matrix_close( + &mapper.map_operator(&op).unwrap().to_matrix().unwrap(), + &expected, + ); + for ((row, col), value) in expected.indexed_iter() { + if value.norm() != 0.0 { + assert_eq!(row.count_ones(), col.count_ones()); + } + } + let number = FermionicOp::total_number(n); + assert!( + number + .try_mul(&op) + .unwrap() + .try_sub(&op.try_mul(&number).unwrap()) + .unwrap() + .normal_order() + .unwrap() + .is_zero() + ); + }; + // Every ordered, disjoint single and double excitation for up to five modes. + for n in 2..=5 { + for source in 0..n { + for target in 0..n { + if source == target { + continue; + } + check(n, &[source], &[target]); + for source2 in 0..n { + if [source, target].contains(&source2) { + continue; + } + for target2 in 0..n { + if [source, target, source2].contains(&target2) { + continue; + } + check(n, &[source, source2], &[target, target2]); + } + } + } + } + } + check(6, &[2, 0, 1], &[4, 5, 3]); +} + +#[test] +fn excitation_generator_evolution_matches_independent_fock_exponential() { + let mapper = JordanWignerMapper::new(); + for (n, sources, targets) in [ + (3, vec![0], vec![2]), + (3, vec![2], vec![0]), + (4, vec![0, 1], vec![2, 3]), + (5, vec![1, 0], vec![4, 2]), + ] { + let op = FermionicOp::excitation_generator(n, &sources, &targets).unwrap(); + let mapped = mapper.map_operator(&op).unwrap(); + assert!(mapped.all_terms_commute()); + let k = + excitation_fock_matrix(n, &sources, &targets).mapv(|g| Complex64::new(0.0, -1.0) * g); + for time in [-0.37, 0.0, 0.61] { + assert_matrix_close( + &bound_evolution(mapped.clone(), time), + &matrix_exp(&k, time), + ); + } + } +} + +#[test] +fn composed_excitations_have_independent_parameters_and_correct_statevectors() { + let mapper = JordanWignerMapper::new(); + let occupation = mapper.map_occupation(&[1, 1, 0, 0]).unwrap(); + let mut circuit = BasisEncoding::new(occupation) + .build_circuit("reference") + .unwrap(); + for (sources, targets, name) in [ + (vec![0, 1], vec![2, 3], "theta_double"), + (vec![0], vec![2], "theta_single"), + ] { + let g = FermionicOp::excitation_generator(4, &sources, &targets).unwrap(); + let block = PauliEvolutionAnsatz::new(mapper.map_operator(&g).unwrap()) + .unwrap() + .with_time_param_name(name) + .with_strategy(EvolutionStrategy::Exact) + .build_circuit("excitation") + .unwrap(); + assert_eq!(block.symbols().len(), 1); + circuit.compose(&block, None).unwrap(); + } + assert_eq!(circuit.symbols().len(), 2); + assert!(circuit.symbols().contains("theta_double")); + assert!(circuit.symbols().contains("theta_single")); + let number = mapper.map_operator(&FermionicOp::total_number(4)).unwrap(); + for (double, single) in [ + (0.0_f64, 0.0_f64), + (0.37, 0.0), + (0.0, -0.21), + (0.37, -0.21), + (-0.43, 0.19), + ] { + // Bind in two stages to exercise independence and partial binding. + let partial = circuit + .assign_parameters(&Some(HashMap::from([("theta_double", double)]))) + .unwrap(); + assert_eq!(partial.symbols().len(), 1); + assert!(partial.symbols().contains("theta_single")); + let bound = partial + .assign_parameters(&Some(HashMap::from([("theta_single", single)]))) + .unwrap(); + assert!(bound.symbols().is_empty()); + let state = Statevector::from_circuit(&bound).unwrap(); + let mut expected = vec![Complex64::new(0.0, 0.0); 16]; + expected[3] = (double.cos() * single.cos()).into(); + expected[6] = (-double.cos() * single.sin()).into(); + expected[12] = (double.sin() * single.cos()).into(); + expected[9] = (-double.sin() * single.sin()).into(); + for (actual, expected) in state.data().iter().zip(expected) { + assert!((*actual - expected).norm() < 1e-11); + } + assert!((number.expectation_statevector(&state).unwrap() - 2.0).abs() < 1e-11); + } +} + +fn matrix_exp(matrix: &Array2, scale: f64) -> Array2 { + let mut term = Array2::::eye(matrix.nrows()); + let mut result = term.clone(); + for order in 1..=48 { + term = term.dot(matrix).mapv(|c| c * scale / order as f64); + result += &term; + } + result +} + +fn bound_evolution(h: Hamiltonian, time: f64) -> Array2 { + let circuit = PauliEvolutionAnsatz::new(h) + .unwrap() + .build_circuit("fermion") + .unwrap(); + let bindings = HashMap::from([("fermion_t", time)]); + let circuit = circuit.assign_parameters(&Some(bindings)).unwrap(); + circuit_to_matrix(&circuit, None).unwrap() +} + +fn pauli_terms(h: &Hamiltonian) -> BTreeMap { + assert!(h.terms.iter().all(|(p, _)| p.phase == Phase::Plus)); + h.terms.iter().map(|(p, c)| (p.to_string(), *c)).collect() +} + +#[test] +fn canonical_anticommutation_relations() { + for p in 0..4 { + for q in 0..4 { + let a = FermionicOp::annihilation(4, p).unwrap(); + let b = FermionicOp::annihilation(4, q).unwrap(); + let bd = b.adjoint(); + let anticommutator = (a.try_mul(&bd).unwrap() + bd.try_mul(&a).unwrap()).unwrap(); + let expected = if p == q { + FermionicOp::identity(4) + } else { + FermionicOp::new(4) + }; + assert_eq!(anticommutator.normal_order().unwrap(), expected); + let annihilators = (a.try_mul(&b).unwrap() + b.try_mul(&a).unwrap()).unwrap(); + assert!(annihilators.normal_order().unwrap().is_zero()); + let creators = + (a.adjoint().try_mul(&bd).unwrap() + bd.try_mul(&a.adjoint()).unwrap()).unwrap(); + assert!(creators.normal_order().unwrap().is_zero()); + } + } +} + +#[test] +fn contractions_and_normal_order_preserve_remaining_branches() { + let a = FermionicOp::annihilation(3, 0).unwrap(); + let ad = a.adjoint(); + let hole = (&a * &ad).unwrap(); + assert_eq!( + hole.normal_order().unwrap(), + (FermionicOp::identity(3) - FermionicOp::number(3, 0).unwrap()).unwrap() + ); + assert_eq!((&hole * &a).unwrap().normal_order().unwrap(), a); + assert_eq!((&ad * &hole).unwrap().normal_order().unwrap(), ad); + let n = FermionicOp::number(3, 0).unwrap(); + assert_eq!((&n * &n).unwrap().normal_order().unwrap(), n); + let input = FermionicOp::from_term( + 3, + [Annihilate(0), Create(0), Create(1), Annihilate(2)], + 1.0.into(), + ) + .unwrap(); + let expected = FermionicOp::from_terms( + 3, + [ + (vec![Create(1), Annihilate(2)], 1.0.into()), + ( + vec![Create(0), Create(1), Annihilate(0), Annihilate(2)], + 1.0.into(), + ), + ], + ) + .unwrap(); + assert_eq!(input.normal_order().unwrap(), expected); + assert_eq!(expected.normal_order().unwrap(), expected); +} + +#[test] +fn long_single_branch_normal_order_preserves_sign_and_nilpotency() { + for n in [399, 400, 799, 800] { + let word: Vec<_> = (0..n).rev().map(Create).collect(); + let input = FermionicOp::from_term(n, word.clone(), 1.0.into()).unwrap(); + let sign = if (n * (n - 1) / 2) % 2 == 0 { + 1.0 + } else { + -1.0 + }; + let expected = FermionicOp::from_term(n, (0..n).map(Create), sign.into()).unwrap(); + assert_eq!(input.normal_order().unwrap(), expected); + assert_eq!(expected.normal_order().unwrap(), expected); + + let mut repeated = word; + repeated.push(Create(n - 1)); + assert!( + FermionicOp::from_term(n, repeated, 1.0.into()) + .unwrap() + .normal_order() + .unwrap() + .is_zero() + ); + } +} + +#[test] +fn multiplication_keeps_order_and_adjoint_reverses_it() { + let a = + FermionicOp::from_term(3, [Create(2), Annihilate(0)], Complex64::new(2.0, 3.0)).unwrap(); + let expected = + FermionicOp::from_term(3, [Create(0), Annihilate(2)], Complex64::new(2.0, -3.0)).unwrap(); + assert_eq!(a.adjoint(), expected); + assert_eq!(a.adjoint().adjoint(), a); + let b = FermionicOp::creation(3, 1).unwrap(); + let product = (&a * &b).unwrap(); + assert_eq!( + product.terms().next().unwrap().0, + [Create(2), Annihilate(0), Create(1)] + ); + assert_eq!(product.adjoint(), (&b.adjoint() * &a.adjoint()).unwrap()); + assert_eq!(Create(1).adjoint(), Annihilate(1)); +} + +#[test] +fn exact_merging_explicit_chopping_and_structural_equality() { + let mut op = FermionicOp::from_terms( + 4, + [ + (vec![Create(1)], 0.5.into()), + (vec![Create(1)], (-0.5).into()), + (vec![Annihilate(3)], Complex64::new(1e-14, 0.0)), + ], + ) + .unwrap(); + assert_eq!(op.num_terms(), 1); + assert_eq!(op.num_modes(), 4); + op.chop(0.0).unwrap(); + assert_eq!(op.num_terms(), 1); + op.chop(1e-14).unwrap(); + assert_eq!(op, FermionicOp::new(4)); + let input = FermionicOp::from_term(2, [Create(1), Create(0)], 1.0.into()).unwrap(); + let ordered = FermionicOp::from_term(2, [Create(0), Create(1)], (-1.0).into()).unwrap(); + assert_ne!(input, ordered); + assert!(input.equiv(&ordered, 0.0).unwrap()); + assert_ne!(FermionicOp::new(1), FermionicOp::new(2)); +} + +#[test] +fn fallible_owned_and_borrowed_arithmetic() { + let a = FermionicOp::creation(2, 0).unwrap(); + let b = FermionicOp::annihilation(2, 1).unwrap(); + let sum = a.try_add(&b).unwrap(); + assert_eq!((&a + &b).unwrap(), sum); + assert_eq!((a.clone() + &b).unwrap(), sum); + assert_eq!((&a + b.clone()).unwrap(), sum); + assert_eq!((a.clone() + b.clone()).unwrap(), sum); + let difference = a.try_sub(&b).unwrap(); + assert_eq!((&a - &b).unwrap(), difference); + assert_eq!((a.clone() - &b).unwrap(), difference); + assert_eq!((&a - b.clone()).unwrap(), difference); + assert_eq!((a.clone() - b.clone()).unwrap(), difference); + let product = a.try_mul(&b).unwrap(); + assert_eq!((&a * &b).unwrap(), product); + assert_eq!((a.clone() * &b).unwrap(), product); + assert_eq!((&a * b.clone()).unwrap(), product); + assert_eq!((a.clone() * b.clone()).unwrap(), product); + for factor in [Complex64::new(2.0, 0.0), Complex64::new(0.0, 1.0)] { + let scaled = a.scaled(factor).unwrap(); + assert_eq!((&a * factor).unwrap(), scaled); + assert_eq!((a.clone() * factor).unwrap(), scaled); + assert_eq!((factor * &a).unwrap(), scaled); + assert_eq!((factor * a.clone()).unwrap(), scaled); + } + assert_eq!((&a * 2.0).unwrap(), (2.0 * &a).unwrap()); + assert_eq!((a.clone() * 2.0).unwrap(), (2.0 * a.clone()).unwrap()); + assert_eq!(-&a, -a.clone()); + assert!((&a + -&a).unwrap().is_zero()); +} + +#[test] +fn invalid_inputs_and_failed_mutation_do_not_corrupt_operators() { + assert!(matches!( + FermionicOp::creation(0, 0), + Err(QisError::ModeOutOfBounds { + mode: 0, + num_modes: 0 + }) + )); + assert!(FermionicOp::annihilation(2, 2).is_err()); + assert!(FermionicOp::number(1, usize::MAX).is_err()); + assert!(FermionicOp::from_term(1, [Create(2)], 0.0.into()).is_err()); + let a = FermionicOp::creation(1, 0).unwrap(); + let b = FermionicOp::new(2); + for result in [&a + &b, &a - &b, &a * &b] { + assert!(matches!( + result, + Err(QisError::ModeMismatch { + expected: 1, + actual: 2 + }) + )); + } + assert!(a.equiv(&b, 0.0).is_err()); + for c in [ + Complex64::new(f64::NAN, 0.0), + Complex64::new(0.0, f64::INFINITY), + ] { + assert!(matches!( + FermionicOp::from_term(1, [], c), + Err(QisError::NonFiniteCoefficient { .. }) + )); + assert!(FermionicOp::new(1).scaled(c).is_err()); + } + let mut large = FermionicOp::from_term(1, [Create(0)], f64::MAX.into()).unwrap(); + let saved = large.clone(); + assert!(large.add_term([Create(0)], f64::MAX.into()).is_err()); + assert_eq!(large, saved); + assert!(large.add_term([Create(1)], 1.0.into()).is_err()); + assert_eq!(large, saved); + assert!(large.scaled(2.0.into()).is_err()); + for tolerance in [-1.0, f64::NAN, f64::INFINITY] { + assert!(large.chop(tolerance).is_err()); + assert_eq!(large, saved); + assert!(large.is_hermitian(tolerance).is_err()); + assert!(large.equiv(&saved, tolerance).is_err()); + } +} + +#[test] +fn hermiticity_checks_use_fermionic_algebra() { + let hole = FermionicOp::from_term(2, [Annihilate(0), Create(0)], 1.0.into()).unwrap(); + assert!(hole.is_hermitian(0.0).unwrap()); + let t = FermionicOp::from_term(2, [Create(1), Annihilate(0)], 1.0.into()).unwrap(); + assert!(!t.is_hermitian(0.0).unwrap()); + let generator = (&t - t.adjoint()) + .unwrap() + .scaled(Complex64::new(0.0, 1.0)) + .unwrap(); + assert!(generator.is_hermitian(0.0).unwrap()); + assert!( + !FermionicOp::identity(0) + .scaled(Complex64::new(0.0, 1.0)) + .unwrap() + .is_hermitian(0.0) + .unwrap() + ); +} + +#[test] +fn ladder_number_hole_and_identity_mappings() { + let mapper = JordanWignerMapper::new(); + let creation = mapper + .map_operator(&FermionicOp::creation(4, 2).unwrap()) + .unwrap(); + assert_eq!( + pauli_terms(&creation), + BTreeMap::from([ + ("+IXZZ".into(), 0.5.into()), + ("+IYZZ".into(), Complex64::new(0.0, -0.5)), + ]) + ); + let annihilation = mapper + .map_operator(&FermionicOp::annihilation(4, 2).unwrap()) + .unwrap(); + assert_eq!( + pauli_terms(&annihilation), + BTreeMap::from([ + ("+IXZZ".into(), 0.5.into()), + ("+IYZZ".into(), Complex64::new(0.0, 0.5)), + ]) + ); + assert_eq!( + pauli_terms( + &mapper + .map_operator(&FermionicOp::number(4, 2).unwrap()) + .unwrap() + ), + BTreeMap::from([ + ("+IIII".into(), 0.5.into()), + ("+IZII".into(), (-0.5).into()), + ]) + ); + let hole = FermionicOp::from_term(4, [Annihilate(2), Create(2)], 1.0.into()).unwrap(); + assert_eq!( + pauli_terms(&mapper.map_operator(&hole).unwrap()), + BTreeMap::from([("+IIII".into(), 0.5.into()), ("+IZII".into(), 0.5.into()),]) + ); + assert_eq!( + pauli_terms(&mapper.map_operator(&FermionicOp::identity(4)).unwrap()), + BTreeMap::from([("+IIII".into(), 1.0.into())]) + ); +} + +#[test] +fn zero_scalar_and_wide_mode_spaces_are_preserved() { + let mapper = JordanWignerMapper::new(); + for n in [0, 1, 4, 129] { + let zero = mapper.map_operator(&FermionicOp::new(n)).unwrap(); + assert_eq!(zero.num_qubits, n); + assert!(zero.terms.is_empty()); + assert_eq!(mapper.num_qubits(n), n); + } + let scalar = FermionicOp::identity(0) + .scaled(Complex64::new(2.0, 3.0)) + .unwrap(); + assert_eq!( + mapper.map_operator(&scalar).unwrap().to_matrix().unwrap()[[0, 0]], + Complex64::new(2.0, 3.0) + ); + assert!(FermionicOp::total_number(0).is_zero()); + let wide = mapper + .map_operator(&FermionicOp::creation(129, 128).unwrap()) + .unwrap(); + assert_eq!(wide.num_qubits, 129); + assert_eq!(wide.terms.len(), 2); + assert!( + wide.terms + .iter() + .all(|(p, _)| (0..128).all(|j| p.get_pauli(j) == crate::qis::Pauli::Z)) + ); + let nilpotent = FermionicOp::from_term(4, [Create(0), Create(0)], 1.0.into()).unwrap(); + let mapped = mapper.map_operator(&nilpotent).unwrap(); + assert!(mapped.terms.is_empty()); + assert_eq!(mapped.num_qubits, 4); +} + +fn check_word(n: usize, word: Vec) { + let op = FermionicOp::from_term(n, word, 1.0.into()).unwrap(); + let normal = op.normal_order().unwrap(); + assert_eq!(normal.normal_order().unwrap(), normal); + let expected = fock_matrix(&op); + assert_matrix_close(&fock_matrix(&normal), &expected); + let mapper = JordanWignerMapper::new(); + assert_matrix_close( + &mapper.map_operator(&op).unwrap().to_matrix().unwrap(), + &expected, + ); + assert_matrix_close( + &mapper.map_operator(&normal).unwrap().to_matrix().unwrap(), + &expected, + ); +} + +#[test] +fn exhaustive_short_products_match_independent_fock_matrices() { + for n in 1usize..=3 { + for length in 0u32..=4 { + for mut encoded in 0..(2 * n).pow(length) { + let word = (0..length) + .map(|_| { + let symbol = encoded % (2 * n); + encoded /= 2 * n; + if symbol < n { + Create(symbol) + } else { + Annihilate(symbol - n) + } + }) + .collect(); + check_word(n, word); + } + } + } +} + +#[test] +fn fixed_seed_longer_products_match_independent_fock_matrices() { + let mut seed = 20261009u64; + for sample in 0..256 { + let word = (0..sample % 9) + .map(|_| { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1); + let symbol = (seed >> 32) as usize % 8; + if symbol < 4 { + Create(symbol) + } else { + Annihilate(symbol - 4) + } + }) + .collect(); + check_word(4, word); + } +} + +#[test] +fn mapping_preserves_linear_combinations_products_and_adjoint() { + let mapper = JordanWignerMapper::new(); + let a = FermionicOp::from_terms( + 3, + [ + (vec![Annihilate(1), Create(2)], Complex64::new(1.0, 2.0)), + (vec![], Complex64::new(-2.0, 1.0)), + ], + ) + .unwrap(); + let b = FermionicOp::creation(3, 0).unwrap(); + let ma = mapper.map_operator(&a).unwrap().to_matrix().unwrap(); + let mb = mapper.map_operator(&b).unwrap().to_matrix().unwrap(); + assert_matrix_close(&ma, &fock_matrix(&a)); + assert_matrix_close( + &mapper + .map_operator(&(&a + &b).unwrap()) + .unwrap() + .to_matrix() + .unwrap(), + &(&ma + &mb), + ); + assert_matrix_close( + &mapper + .map_operator(&(&a * &b).unwrap()) + .unwrap() + .to_matrix() + .unwrap(), + &ma.dot(&mb), + ); + assert_matrix_close( + &mapper + .map_operator(&a.adjoint()) + .unwrap() + .to_matrix() + .unwrap(), + &ma.t().mapv(|c| c.conj()), + ); +} + +#[test] +fn occupation_encoding_prepares_basis_states_and_number_observables() { + let mapper = JordanWignerMapper::new(); + let operator_mapper: &dyn FermionToQubitMapper = &mapper; + let state_mapper: &dyn OccupationStateMapper = &mapper; + for n in 1..=4 { + let number = operator_mapper + .map_operator(&FermionicOp::total_number(n)) + .unwrap(); + for state in 0usize..1 << n { + let occupation: Vec<_> = (0..n).map(|p| ((state >> p) & 1) as u8).collect(); + let bits = state_mapper.map_occupation(&occupation).unwrap(); + let circuit = BasisEncoding::new(bits) + .build_circuit("occupation") + .unwrap(); + let sv = Statevector::from_circuit(&circuit).unwrap(); + assert_eq!(sv.probabilities()[state], 1.0); + assert_eq!( + number.expectation_statevector(&sv).unwrap(), + state.count_ones() as f64 + ); + assert_eq!(number.variance_statevector(&sv).unwrap(), 0.0); + let dm = DensityMatrix::from_circuit(&circuit).unwrap(); + assert_eq!( + number.expectation_density_matrix(&dm).unwrap(), + state.count_ones() as f64 + ); + for (p, occupation_value) in occupation.iter().enumerate() { + let np = operator_mapper + .map_operator(&FermionicOp::number(n, p).unwrap()) + .unwrap(); + assert_eq!( + np.expectation_statevector(&sv).unwrap(), + *occupation_value as f64 + ); + } + } + } + assert_eq!(mapper.map_occupation(&[]).unwrap(), Vec::::new()); + for invalid in [2, 255] { + assert!( + matches!(mapper.map_occupation(&[1, invalid]), Err(QisError::InvalidOccupation { index: 1, value }) if value == invalid) + ); + } +} + +#[test] +fn single_and_double_excitation_evolution_matches_fock_exponentials() { + let mapper = JordanWignerMapper::new(); + for (n, word) in [ + (3, vec![Create(2), Annihilate(0)]), + (4, vec![Create(2), Create(3), Annihilate(1), Annihilate(0)]), + ] { + let t = FermionicOp::from_term(n, word, 1.0.into()).unwrap(); + let k = (&t - t.adjoint()).unwrap(); + let h = k.scaled(Complex64::new(0.0, 1.0)).unwrap(); + let mapped = mapper.map_operator(&h).unwrap(); + assert!(mapped.all_terms_commute()); + let time = 0.37; + let expected = matrix_exp(&fock_matrix(&k), time); + assert_matrix_close(&bound_evolution(mapped.clone(), time), &expected); + let numeric = mapped + .to_evolution_circuit(time, 1, TrotterMode::FirstOrder) + .unwrap(); + assert_matrix_close(&circuit_to_matrix(&numeric, None).unwrap(), &expected); + let particle_number = fock_matrix(&FermionicOp::total_number(n)); + let generator = fock_matrix(&k); + assert_matrix_close( + &particle_number.dot(&generator), + &generator.dot(&particle_number), + ); + } +} + +#[test] +fn reversing_double_excitation_annihilators_changes_the_sign() { + let a = FermionicOp::from_term( + 4, + [Create(2), Create(3), Annihilate(1), Annihilate(0)], + 1.0.into(), + ) + .unwrap(); + let b = FermionicOp::from_term( + 4, + [Create(2), Create(3), Annihilate(0), Annihilate(1)], + 1.0.into(), + ) + .unwrap(); + assert!((&a + &b).unwrap().normal_order().unwrap().is_zero()); + assert_eq!(fock_matrix(&a)[[12, 3]], Complex64::new(1.0, 0.0)); + assert_matrix_close(&fock_matrix(&b), &fock_matrix(&a).mapv(|c| -c)); +} + +#[test] +fn small_coefficients_survive_mapping_and_both_evolution_apis() { + let mapper = JordanWignerMapper::new(); + let t = FermionicOp::creation(1, 0).unwrap(); + let k = (&t - t.adjoint()).unwrap(); + let tiny = k.scaled(Complex64::new(0.0, 1e-12)).unwrap(); + let mapped = mapper.map_operator(&tiny).unwrap(); + assert_eq!(mapped.terms.len(), 1); + assert_eq!(mapped.terms[0].1, Complex64::new(1e-12, 0.0)); + assert_eq!( + PauliEvolutionAnsatz::new(mapped.clone()) + .unwrap() + .evolution_info() + .num_terms, + 1 + ); + // Large time makes loss of a small coefficient observable in the matrix. + let numeric = mapped + .to_evolution_circuit(1e12, 1, TrotterMode::FirstOrder) + .unwrap(); + let expected = matrix_exp(&fock_matrix(&k), 1.0); + assert_matrix_close(&circuit_to_matrix(&numeric, None).unwrap(), &expected); + assert_matrix_close(&bound_evolution(mapped, 1e12), &expected); +} + +#[test] +fn identity_evolution_preserves_global_phase_and_nonhermitian_mapping_is_allowed() { + let mapper = JordanWignerMapper::new(); + let h = mapper + .map_operator(&FermionicOp::identity(2).scaled(0.3.into()).unwrap()) + .unwrap(); + let expected = Array2::::eye(4).mapv(|c| c * Complex64::from_polar(1.0, -0.15)); + assert_matrix_close(&bound_evolution(h, 0.5), &expected); + let creation = mapper + .map_operator(&FermionicOp::creation(2, 0).unwrap()) + .unwrap(); + assert!(matches!( + PauliEvolutionAnsatz::new(creation), + Err(QisError::NotHermitian) + )); + assert!(PauliEvolutionAnsatz::new(mapper.map_operator(&FermionicOp::new(2)).unwrap()).is_err()); +} + +#[test] +fn mapping_reports_coefficient_overflow_after_pauli_merging() { + let op = FermionicOp::from_terms( + 1, + [ + (vec![], f64::MAX.into()), + (vec![Create(0), Annihilate(0)], f64::MAX.into()), + (vec![Annihilate(0), Create(0)], f64::MAX.into()), + ], + ) + .unwrap(); + assert!(matches!( + JordanWignerMapper::new().map_operator(&op), + Err(QisError::NonFiniteCoefficient { .. }) + )); +} + +#[test] +fn mapping_applies_subnormal_weights_after_merging_the_unit_product() { + let tiny = f64::from_bits(2); + let half = f64::from_bits(1); + let mapper = JordanWignerMapper::new(); + for coefficient in [ + Complex64::new(tiny, 0.0), + Complex64::new(0.0, -tiny), + Complex64::new(tiny, -tiny), + ] { + for (word, z_sign) in [ + (vec![Create(0), Annihilate(0)], -1.0), + (vec![Annihilate(0), Create(0)], 1.0), + ( + vec![Create(0), Annihilate(0), Create(0), Annihilate(0)], + -1.0, + ), + ] { + let input = FermionicOp::from_term(1, word, coefficient).unwrap(); + let mapped = mapper.map_operator(&input).unwrap(); + let expected_half = Complex64::new( + if coefficient.re == 0.0 { 0.0 } else { half }, + if coefficient.im == 0.0 { 0.0 } else { -half }, + ); + // Compare coefficients exactly: a matrix tolerance would hide subnormals. + assert_eq!( + pauli_terms(&mapped), + BTreeMap::from([ + ("+I".into(), expected_half), + ("+Z".into(), expected_half * z_sign), + ]) + ); + } + let identity = FermionicOp::identity(1).scaled(coefficient).unwrap(); + assert_eq!( + pauli_terms(&mapper.map_operator(&identity).unwrap()), + BTreeMap::from([("+I".into(), coefficient)]) + ); + } +} + +#[test] +fn normal_order_and_arithmetic_report_coefficient_overflow() { + let op = FermionicOp::from_terms( + 1, + [ + (vec![Create(0)], f64::MAX.into()), + (vec![Create(0), Annihilate(0), Create(0)], f64::MAX.into()), + ], + ) + .unwrap(); + assert!(matches!( + op.normal_order(), + Err(QisError::NonFiniteCoefficient { .. }) + )); + let a = FermionicOp::from_term(1, [Create(0)], f64::MAX.into()).unwrap(); + assert!((&a + &a).is_err()); + let twice_identity = FermionicOp::identity(1).scaled(2.0.into()).unwrap(); + assert!((&a * twice_identity).is_err()); + let tiny = FermionicOp::creation(1, 0) + .unwrap() + .scaled(1e-310.into()) + .unwrap(); + let mut retained = tiny.clone(); + retained.chop(0.0).unwrap(); + assert_eq!(retained, tiny); + assert_eq!( + JordanWignerMapper::new() + .map_operator(&tiny) + .unwrap() + .terms + .len(), + 2 + ); +} + +#[test] +fn noncommuting_excitation_sum_uses_the_same_numeric_and_symbolic_product_formula() { + let first = FermionicOp::from_term(3, [Create(1), Annihilate(0)], 1.0.into()).unwrap(); + let second = FermionicOp::from_term(3, [Create(2), Annihilate(1)], 1.0.into()).unwrap(); + let t = (&first + &second).unwrap(); + let k = (&t - t.adjoint()).unwrap(); + let h = JordanWignerMapper::new() + .map_operator(&k.scaled(Complex64::new(0.0, 1.0)).unwrap()) + .unwrap(); + assert!(!h.all_terms_commute()); + assert!( + PauliEvolutionAnsatz::new(h.clone()) + .unwrap() + .with_strategy(EvolutionStrategy::Exact) + .build_circuit("exact") + .is_err() + ); + let time = 0.2; + let numeric = h + .to_evolution_circuit(time, 8, TrotterMode::SecondOrder) + .unwrap(); + let numeric = circuit_to_matrix(&numeric, None).unwrap(); + let circuit = PauliEvolutionAnsatz::new(h) + .unwrap() + .with_strategy(EvolutionStrategy::Trotter { + mode: TrotterMode::SecondOrder, + steps: 8, + }) + .build_circuit("sum") + .unwrap(); + let circuit = circuit + .assign_parameters(&Some(HashMap::from([("sum_t", time)]))) + .unwrap(); + assert_matrix_close(&numeric, &circuit_to_matrix(&circuit, None).unwrap()); + let expected = matrix_exp(&fock_matrix(&k), time); + assert!((&numeric - &expected).iter().all(|c| c.norm() < 1e-3)); +} + +#[test] +fn all_hamiltonian_consumers_validate_original_and_merged_inputs() { + let sv = Statevector::new(1); + let dm = DensityMatrix::new(1); + let x: PauliString = "X".parse().unwrap(); + let mut malformed = x.clone(); + malformed.z.clear(); + let invalid = [ + Hamiltonian { + num_qubits: 1, + terms: vec![(PauliString::new(2), 1.0.into())], + }, + Hamiltonian { + num_qubits: 1, + terms: vec![(malformed, 1.0.into())], + }, + Hamiltonian { + num_qubits: 1, + terms: vec![(x.clone(), f64::NAN.into())], + }, + Hamiltonian { + num_qubits: 1, + terms: vec![ + (x.clone(), f64::INFINITY.into()), + (x.clone(), f64::NEG_INFINITY.into()), + ], + }, + Hamiltonian { + num_qubits: 1, + terms: vec![(x.clone(), f64::MAX.into()), (x.clone(), f64::MAX.into())], + }, + ]; + for h in invalid { + assert!(h.expectation_statevector(&sv).is_err()); + assert!(h.expectation_density_matrix(&dm).is_err()); + assert!(h.expectation_probs(&[]).is_err()); + assert!(h.variance_statevector(&sv).is_err()); + assert!( + h.to_evolution_circuit(1.0, 1, TrotterMode::FirstOrder) + .is_err() + ); + assert!( + h.to_trotter_circuit(1.0, 1, TrotterMode::FirstOrder) + .is_err() + ); + assert!(PauliEvolutionAnsatz::new(h).is_err()); + } + let zero = Hamiltonian::from_list(vec![(x.clone(), 1.0.into()), (x, (-1.0).into())]).unwrap(); + assert_eq!(zero.expectation_statevector(&sv).unwrap(), 0.0); + assert_eq!(zero.expectation_probs(&[]).unwrap(), 0.0); + for mode in [ + TrotterMode::FirstOrder, + TrotterMode::SecondOrder, + TrotterMode::Randomized(7), + ] { + for circuit in [ + zero.to_evolution_circuit(1.0, 3, mode).unwrap(), + zero.to_trotter_circuit(1.0, 3, mode).unwrap(), + ] { + assert_eq!(circuit.num_qubits(), 1); + assert_eq!(circuit_to_matrix(&circuit, None).unwrap(), Array2::eye(2)); + } + } + assert!(PauliEvolutionAnsatz::new(zero).is_err()); +} + +#[test] +fn hamiltonian_consumers_preserve_coefficient_error_categories() { + let sv = Statevector::new(1); + let dm = DensityMatrix::new(1); + let x: PauliString = "X".parse().unwrap(); + for coefficients in [ + vec![f64::NAN], + vec![f64::INFINITY], + vec![f64::MAX, f64::MAX], + ] { + let h = Hamiltonian::from_list( + coefficients + .into_iter() + .map(|c| (x.clone(), c.into())) + .collect(), + ) + .unwrap(); + for result in [ + h.expectation_statevector(&sv), + h.expectation_density_matrix(&dm), + h.expectation_probs(&[]), + h.variance_statevector(&sv), + ] { + assert!(matches!(result, Err(QisError::InvalidParameterValue(_)))); + } + for result in [ + h.to_evolution_circuit(1.0, 1, TrotterMode::FirstOrder), + h.to_trotter_circuit(1.0, 1, TrotterMode::FirstOrder), + ] { + assert!(matches!(result, Err(QisError::UnsupportedOperation(_)))); + } + } +} diff --git a/crates/cqlib-core/src/qis/hamiltonian.rs b/crates/cqlib-core/src/qis/hamiltonian.rs index 71a1819d..f82d67e2 100644 --- a/crates/cqlib-core/src/qis/hamiltonian.rs +++ b/crates/cqlib-core/src/qis/hamiltonian.rs @@ -13,10 +13,14 @@ //! Hamiltonian representation and operations. //! //! This module provides the [`Hamiltonian`] struct, which represents a quantum -//! observable as a linear combination of Pauli strings (tensor products of Pauli operators) +//! operator as a linear combination of Pauli strings (tensor products of Pauli operators) //! with complex coefficients. It is primarily used for defining system energies, //! observables for expectation value calculations, and operators for time evolution. +//! +//! General algebra permits non-Hermitian operators. Real observables and unitary +//! evolution validate Hermiticity at their consumption boundaries. +use crate::qis::error::validate_coefficient; use crate::qis::pauli::PauliString; use crate::qis::{Phase, QisError}; use ndarray::Array2; @@ -29,6 +33,10 @@ use std::ops::Add; /// A `Hamiltonian` is essentially a sparse representation of a $2^N \times 2^N$ /// matrix, expressed as $H = \sum_k c_k P_k$, where $c_k$ is a complex coefficient /// and $P_k$ is an $N$-qubit Pauli string. +/// +/// Despite its name, this type also represents non-Hermitian operators. Checked +/// algebra returns phase-normalized, merged terms without approximate pruning. +/// [`PartialEq`] compares stored structure; use [`Self::equiv`] for algebraic comparison. #[derive(Debug, Clone, PartialEq)] pub struct Hamiltonian { /// The number of qubits this operator acts on. @@ -51,6 +59,56 @@ impl fmt::Display for Hamiltonian { } impl Hamiltonian { + /// Returns a validated Pauli sum with phases absorbed and exact zeros removed. + /// Retains the declared qubit count, including for zero and scalar operators. + pub fn normalized(&self) -> Result { + Self::from_terms(self.num_qubits, self.terms.iter().cloned()) + } + + fn validate(&self) -> Result<(), QisError> { + for (pauli, coefficient) in &self.terms { + if pauli.num_qubits != self.num_qubits { + return Err(QisError::QubitMismatch { + expected: self.num_qubits, + actual: pauli.num_qubits, + }); + } + for actual in [pauli.x.len(), pauli.z.len()] { + if actual != self.num_qubits { + return Err(QisError::DimensionMismatch { + expected: self.num_qubits, + actual, + }); + } + } + validate_coefficient(*coefficient)?; + } + Ok(()) + } + + /// Shared contract for real-valued observables and Hamiltonian evolution. + /// After merging and absorbing Pauli phases, imaginary parts with magnitude + /// greater than `1e-10` are rejected. Accepted imaginary roundoff residuals + /// are projected to zero, and terms with exactly zero real part are removed. + /// Every nonzero real coefficient is retained, however small. + pub fn normalized_hermitian(&self) -> Result { + let mut normalized = self.normalized()?; + if normalized + .terms + .iter() + .any(|(_, coefficient)| coefficient.im.abs() > 1e-10) + { + return Err(QisError::NotHermitian); + } + for (_, coefficient) in &mut normalized.terms { + coefficient.im = 0.0; + } + normalized + .terms + .retain(|(_, coefficient)| coefficient.re != 0.0); + Ok(normalized) + } + /// Creates a new empty Hamiltonian. /// /// The resulting Hamiltonian represents the zero operator for the given @@ -82,25 +140,49 @@ impl Hamiltonian { /// /// # Errors /// - /// Returns [`QisError::QubitMismatch`] when a term's qubit count differs - /// from [`Hamiltonian::num_qubits`]. + /// Validates term widths, bit-vector lengths and finite coefficients. Returns + /// [`QisError::UnsupportedOperation`] if the dense allocation size overflows + /// or its reservation fails. Matrix-entry overflow is also reported. pub fn to_matrix(&self) -> Result, QisError> { - for (pauli, _) in &self.terms { - if pauli.num_qubits != self.num_qubits { - return Err(QisError::QubitMismatch { - expected: self.num_qubits, - actual: pauli.num_qubits, - }); - } + let normalized = self.normalized()?; + let size_error = || { + QisError::UnsupportedOperation( + "dense Pauli matrix exceeds addressable allocation size".into(), + ) + }; + let shift = u32::try_from(self.num_qubits).map_err(|_| size_error())?; + let dim = 1usize.checked_shl(shift).ok_or_else(size_error)?; + let len = dim.checked_mul(dim).ok_or_else(size_error)?; + let bytes = len + .checked_mul(std::mem::size_of::()) + .ok_or_else(size_error)?; + if bytes > isize::MAX as usize { + return Err(size_error()); } - - let dim = 1usize << self.num_qubits; - let mut matrix = Array2::from_elem((dim, dim), Complex64::new(0.0, 0.0)); - for (pauli, coefficient) in &self.terms { - let term = pauli.to_matrix().mapv(|value| value * *coefficient); - matrix += &term; + let mut data = Vec::new(); + data.try_reserve_exact(len).map_err(|error| { + QisError::UnsupportedOperation(format!("cannot allocate dense Pauli matrix: {error}")) + })?; + data.resize(len, Complex64::new(0.0, 0.0)); + // P|column> flips X bits; Z parity is evaluated before those flips. + for (pauli, coefficient) in &normalized.terms { + let x = pauli.x_mask(); + let z = pauli.z_mask(); + let factor = *coefficient * pauli.y_phase(); + validate_coefficient(factor)?; + for column in 0..dim { + let sign = if (column & z).count_ones() & 1 == 0 { + 1.0 + } else { + -1.0 + }; + let entry = &mut data[(column ^ x) * dim + column]; + *entry += factor * sign; + validate_coefficient(*entry)?; + } } - Ok(matrix) + Array2::from_shape_vec((dim, dim), data) + .map_err(|error| QisError::UnsupportedOperation(error.to_string())) } /// Creates a Hamiltonian from a list of Pauli strings and their corresponding coefficients. @@ -127,6 +209,236 @@ impl From for Hamiltonian { } } +impl Hamiltonian { + /// The identity on the declared register; at zero qubits this is scalar one. + pub fn identity(num_qubits: usize) -> Self { + Self::from_pauli(PauliString::new(num_qubits)) + } + + /// Constructs a validated, phase-normalized sum, merging duplicate terms. + /// Only exact zeros are removed, and empty input retains `num_qubits`. + /// + /// Invalid widths, bit-vector lengths, nonfinite coefficients and intermediate + /// coefficient overflow return an error. No approximate truncation occurs. + pub fn from_terms( + num_qubits: usize, + terms: impl IntoIterator, + ) -> Result { + let mut result = Self { + num_qubits, + terms: terms.into_iter().collect(), + }; + result.validate()?; + result.merge_terms(0.0, true)?; + Ok(result) + } + + fn check_width(&self, other: &Self) -> Result<(), QisError> { + if self.num_qubits != other.num_qubits { + return Err(QisError::QubitMismatch { + expected: self.num_qubits, + actual: other.num_qubits, + }); + } + Ok(()) + } + + fn check_materialized_width(width: usize) -> Result<(), QisError> { + // BitSlice reserves metadata bits, so its length bound is below usize::MAX. + // Zero sums need no bit vectors and may retain larger declared widths. + if width > bitvec::slice::BitSlice::::MAX_BITS { + return Err(QisError::UnsupportedOperation( + "Pauli register width exceeds the BitVec representation limit".into(), + )); + } + Ok(()) + } + + /// Adds two operators on the same register, without modifying either input. + /// Unlike legacy `Add`, this validates inputs and merges the resulting terms. + pub fn try_add(&self, other: &Self) -> Result { + self.check_width(other)?; + let left = self.normalized()?; + let right = other.normalized()?; + Self::from_terms(self.num_qubits, left.terms.into_iter().chain(right.terms)) + } + + /// Subtracts two operators on the same register, retaining every nonzero term. + pub fn try_sub(&self, other: &Self) -> Result { + self.check_width(other)?; + let left = self.normalized()?; + let right = other.normalized()?; + Self::from_terms( + self.num_qubits, + left.terms + .into_iter() + .chain(right.terms.into_iter().map(|(p, c)| (p, -c))), + ) + } + + /// Forms the matrix product `self * other`; the right operand acts first. + /// Both inputs are validated even when either represents zero. Products may + /// be non-Hermitian. Expansion takes O(m k n) work before sorting/merging + /// and may generate m k terms, for term counts m, k and register width n. + /// + /// ``` + /// use cqlib_core::qis::{Hamiltonian, QisError}; + /// use num_complex::Complex64; + /// let x = Hamiltonian::from_pauli("X".parse()?); + /// let z = Hamiltonian::from_pauli("Z".parse()?); + /// let minus_i_y = Hamiltonian::from_terms(1, [ + /// ("Y".parse()?, Complex64::new(0.0, -1.0)), + /// ])?; + /// assert!(x.try_mul(&z)?.equiv(&minus_i_y, 0.0)?); + /// # Ok::<(), QisError>(()) + /// ``` + pub fn try_mul(&self, other: &Self) -> Result { + self.check_width(other)?; + let left = self.normalized()?; + let right = other.normalized()?; + Self::from_terms( + self.num_qubits, + left.terms + .iter() + .flat_map(|(p, a)| right.terms.iter().map(move |(q, b)| (p * q, *a * *b))), + ) + } + + /// Returns a scaled sum, checking the factor even for the zero operator. + pub fn scaled(&self, factor: Complex64) -> Result { + validate_coefficient(factor)?; + let normalized = self.normalized()?; + Self::from_terms( + self.num_qubits, + normalized.terms.into_iter().map(|(p, c)| (p, c * factor)), + ) + } + + /// Returns the conjugate transpose after absorbing Pauli phases. + /// Phase-free Pauli strings are Hermitian, so their coefficients are conjugated. + pub fn adjoint(&self) -> Result { + let mut result = self.normalized()?; + for (_, coefficient) in &mut result.terms { + *coefficient = coefficient.conj(); + } + Ok(result) + } + + fn validate_tolerance(atol: f64) -> Result<(), QisError> { + if !atol.is_finite() || atol < 0.0 { + return Err(QisError::InvalidParameterValue( + "Pauli coefficient tolerance must be finite and nonnegative".into(), + )); + } + Ok(()) + } + + /// Normalizes, then removes coefficients with complex magnitude at most `atol`. + /// On any validation or merging error, the stored operator is unchanged. + pub fn chop(&mut self, atol: f64) -> Result<(), QisError> { + Self::validate_tolerance(atol)?; + let mut result = self.normalized()?; + result.terms.retain(|(_, c)| c.norm() > atol); + *self = result; + Ok(()) + } + + /// Compares normalized coefficients of `self - other` against `atol`. + /// Width mismatch is an error. This coefficient tolerance is not a matrix + /// operator-norm bound, and differs from structural `PartialEq`. + pub fn equiv(&self, other: &Self, atol: f64) -> Result { + Self::validate_tolerance(atol)?; + Ok(self + .try_sub(other)? + .terms + .iter() + .all(|(_, c)| c.norm() <= atol)) + } + + /// Checks `self.equiv(self.adjoint(), atol)` as for `FermionicOp`. + /// On a normalized sum this bounds twice the imaginary coefficient magnitude. + /// It does not project coefficients to real values; `normalized_hermitian` + /// retains its separate consumer contract (imaginary tolerance `1e-10`). + pub fn is_hermitian(&self, atol: f64) -> Result { + Self::validate_tolerance(atol)?; + self.equiv(&self.adjoint()?, atol) + } + + /// Returns `self ⊗ other`: `other` occupies low qubits and `self` high qubits. + /// Register widths are added even for zero operators. No dense matrix is built. + /// A nonzero result with a width beyond BitVec's length limit returns an error. + /// + /// ``` + /// use cqlib_core::qis::{Hamiltonian, QisError}; + /// let x = Hamiltonian::from_pauli("X".parse()?); + /// let z = Hamiltonian::from_pauli("Z".parse()?); + /// assert!(x.tensor(&z)?.equiv(&Hamiltonian::from_pauli("XZ".parse()?), 0.0)?); + /// # Ok::<(), QisError>(()) + /// ``` + pub fn tensor(&self, other: &Self) -> Result { + let width = self + .num_qubits + .checked_add(other.num_qubits) + .ok_or_else(|| { + QisError::InvalidParameterValue("tensor register width overflow".into()) + })?; + let left = self.normalized()?; + let right = other.normalized()?; + if !left.terms.is_empty() && !right.terms.is_empty() { + Self::check_materialized_width(width)?; + } + Self::from_terms( + width, + left.terms.iter().flat_map(|(p, a)| { + right.terms.iter().map(move |(q, b)| { + let mut product = q.clone(); + product.x.extend_from_bitslice(&p.x); + product.z.extend_from_bitslice(&p.z); + product.num_qubits = width; + (product, *a * *b) + }) + }), + ) + } + + /// Relabels qubits using `mapping[source] = destination`, inserting identities + /// on unused target qubits. Requires exactly one distinct destination per + /// source qubit, each less than `target_width`, even for zero/identity input. + /// This is a qubit embedding, not a fermionic mode permutation or a trace. + /// If terms must be constructed, unrepresentable target widths return + /// [`QisError::UnsupportedOperation`] before BitVec allocation. + pub fn remap_qubits(&self, mapping: &[usize], target_width: usize) -> Result { + if mapping.len() != self.num_qubits { + return Err(QisError::InvalidParameterValue( + "qubit mapping length mismatch".into(), + )); + } + let mut destinations = std::collections::HashSet::with_capacity(mapping.len()); + for &destination in mapping { + if destination >= target_width || !destinations.insert(destination) { + return Err(QisError::InvalidParameterValue( + "qubit mapping must contain distinct, in-range destinations".into(), + )); + } + } + let normalized = self.normalized()?; + if !normalized.terms.is_empty() { + Self::check_materialized_width(target_width)?; + } + Self::from_terms( + target_width, + normalized.terms.into_iter().map(|(p, c)| { + let mut mapped = PauliString::new(target_width); + for (source, &destination) in mapping.iter().enumerate() { + mapped.x.set(destination, p.x[source]); + mapped.z.set(destination, p.z[source]); + } + (mapped, c) + }), + ) + } +} + impl TryFrom> for Hamiltonian { type Error = QisError; @@ -190,8 +502,19 @@ impl Hamiltonian { /// /// This method is crucial for optimizing performance before executing quantum simulations. pub fn simplify(&mut self) { + self.simplify_with_tolerance(1e-10); + } + + // Evolution must merge terms without pruning small, nonzero coefficients. + pub(crate) fn simplify_with_tolerance(&mut self, tolerance: f64) { + // Legacy simplification retains its infallible API and numerical behavior. + self.merge_terms(tolerance, false) + .expect("unchecked merging cannot fail"); + } + + fn merge_terms(&mut self, tolerance: f64, checked: bool) -> Result<(), QisError> { if self.terms.is_empty() { - return; + return Ok(()); } // 1. Normalize the Phase of all PauliStrings to Plus (+1), and multiply the phase into the coefficient. @@ -208,6 +531,9 @@ impl Hamiltonian { // Multiply the phase into the coefficient let new_coeff = coeff * phase_val; + if checked { + validate_coefficient(new_coeff)?; + } simplified_terms.push((pure_op, new_coeff)); } @@ -232,10 +558,15 @@ impl Hamiltonian { if op.x == current_op.x && op.z == current_op.z { // Identical operator found, accumulate the coefficient current_coeff += coeff; + if checked { + validate_coefficient(current_coeff)?; + } } else { // New operator found, save the previous one if its coefficient is significant // Filter out terms with a coefficient near zero - if current_coeff.norm() > 1e-10 { + if (tolerance == 0.0 && current_coeff != Complex64::new(0.0, 0.0)) + || current_coeff.norm() > tolerance + { merged.push((current_op, current_coeff)); } current_op = op; @@ -243,12 +574,15 @@ impl Hamiltonian { } } // Push the last accumulated term - if current_coeff.norm() > 1e-10 { + if (tolerance == 0.0 && current_coeff != Complex64::new(0.0, 0.0)) + || current_coeff.norm() > tolerance + { merged.push((current_op, current_coeff)); } } self.terms = merged; + Ok(()) } /// Scales all terms in the Hamiltonian by a complex factor. diff --git a/crates/cqlib-core/src/qis/hamiltonian_test.rs b/crates/cqlib-core/src/qis/hamiltonian_test.rs index c3a0417f..be4c2b05 100644 --- a/crates/cqlib-core/src/qis/hamiltonian_test.rs +++ b/crates/cqlib-core/src/qis/hamiltonian_test.rs @@ -15,6 +15,547 @@ use crate::qis::{PauliString, Phase, QisError}; use ndarray::{Array2, arr2}; use num_complex::Complex64; +/// Test-only Kronecker product, independent of production Pauli operations. +fn matrix_tensor(a: &Array2, b: &Array2) -> Array2 { + Array2::from_shape_fn((a.nrows() * b.nrows(), a.ncols() * b.ncols()), |(r, c)| { + a[[r / b.nrows(), c / b.ncols()]] * b[[r % b.nrows(), c % b.ncols()]] + }) +} + +fn matrix_adjoint(a: &Array2) -> Array2 { + a.t().mapv(|c| c.conj()) +} + +/// Literal single-qubit matrices and explicit labels, not production masks/phases. +fn matrix_oracle(terms: &[(&str, Phase, Complex64)]) -> Array2 { + let width = terms[0].0.len(); + let mut sum = Array2::zeros((1 << width, 1 << width)); + let zero = Complex64::new(0.0, 0.0); + let one = Complex64::new(1.0, 0.0); + let i = Complex64::new(0.0, 1.0); + for &(label, phase, coefficient) in terms { + let mut product = arr2(&[[one]]); + for letter in label.chars() { + let local = match letter { + 'I' => arr2(&[[one, zero], [zero, one]]), + 'X' => arr2(&[[zero, one], [one, zero]]), + 'Y' => arr2(&[[zero, -i], [i, zero]]), + 'Z' => arr2(&[[one, zero], [zero, -one]]), + _ => panic!("invalid test label"), + }; + product = matrix_tensor(&product, &local); + } + let phase = match phase { + Phase::Plus => one, + Phase::Minus => -one, + Phase::I => i, + Phase::MinusI => -i, + }; + sum += &product.mapv(|c| c * phase * coefficient); + } + sum +} + +fn raw_sum(terms: &[(&str, Phase, Complex64)]) -> Hamiltonian { + Hamiltonian::from_list( + terms + .iter() + .map(|&(label, phase, coefficient)| { + let mut pauli: PauliString = label.parse().unwrap(); + pauli.phase = phase; + (pauli, coefficient) + }) + .collect(), + ) + .unwrap() +} + +fn assert_matrix_close(actual: &Array2, expected: &Array2) { + assert_eq!(actual.dim(), expected.dim()); + for (a, b) in actual.iter().zip(expected) { + assert!((*a - *b).norm() < 1e-12, "{actual:?} != {expected:?}"); + } +} + +#[test] +fn sparse_arithmetic_matches_independent_matrices() { + let a_terms = [ + ("XYZ", Phase::MinusI, Complex64::new(0.5, 0.25)), + ("XYZ", Phase::Plus, Complex64::new(-0.125, 0.75)), + ("YIX", Phase::Minus, Complex64::new(1.0, -0.5)), + ("III", Phase::I, Complex64::new(-0.25, 0.5)), + ]; + let b_terms = [ + ("ZZY", Phase::I, Complex64::new(0.75, -0.25)), + ("XYY", Phase::Plus, Complex64::new(-0.5, 0.5)), + ]; + let a = raw_sum(&a_terms); + let b = raw_sum(&b_terms); + let saved = (a.clone(), b.clone()); + let am = matrix_oracle(&a_terms); + let bm = matrix_oracle(&b_terms); + assert_matrix_close(&a.to_matrix().unwrap(), &am); + assert_matrix_close(&a.try_add(&b).unwrap().to_matrix().unwrap(), &(&am + &bm)); + assert_matrix_close(&a.try_sub(&b).unwrap().to_matrix().unwrap(), &(&am - &bm)); + assert_matrix_close(&a.try_mul(&b).unwrap().to_matrix().unwrap(), &am.dot(&bm)); + assert_matrix_close( + &a.adjoint().unwrap().to_matrix().unwrap(), + &matrix_adjoint(&am), + ); + let factor = Complex64::new(0.25, -0.5); + assert_matrix_close( + &a.scaled(factor).unwrap().to_matrix().unwrap(), + &am.mapv(|c| c * factor), + ); + assert_eq!((a, b), saved); +} + +#[test] +fn exhaustive_two_qubit_products_include_all_global_phases() { + for a in ['I', 'X', 'Y', 'Z'] { + for b in ['I', 'X', 'Y', 'Z'] { + for c in ['I', 'X', 'Y', 'Z'] { + for d in ['I', 'X', 'Y', 'Z'] { + for phase in [Phase::Plus, Phase::Minus, Phase::I, Phase::MinusI] { + let left_label = format!("{a}{b}"); + let right_label = format!("{c}{d}"); + let left = [(left_label.as_str(), phase, Complex64::new(0.5, 0.25))]; + let right = [( + right_label.as_str(), + Phase::MinusI, + Complex64::new(-0.25, 0.5), + )]; + let product = raw_sum(&left).try_mul(&raw_sum(&right)).unwrap(); + assert_matrix_close( + &product.to_matrix().unwrap(), + &matrix_oracle(&left).dot(&matrix_oracle(&right)), + ); + } + } + } + } + } +} + +#[test] +fn cancellations_and_adjoint_product_order_follow_operator_algebra() { + let x = Hamiltonian::from_pauli("X".parse().unwrap()); + let z = Hamiltonian::from_pauli("Z".parse().unwrap()); + let sum = x.try_add(&z).unwrap(); + assert_eq!( + sum.try_mul(&sum).unwrap(), + Hamiltonian::identity(1).scaled(2.0.into()).unwrap() + ); + let product = x.try_mul(&z).unwrap(); + assert_eq!( + product.terms, + vec![("Y".parse().unwrap(), Complex64::new(0.0, -1.0))] + ); + assert!(!product.is_hermitian(0.0).unwrap()); + assert_eq!( + product.adjoint().unwrap(), + z.adjoint().unwrap().try_mul(&x.adjoint().unwrap()).unwrap() + ); + let commutator = product.try_sub(&z.try_mul(&x).unwrap()).unwrap(); + assert_eq!(commutator.terms[0].1, Complex64::new(0.0, -2.0)); + assert!( + product + .try_add(&z.try_mul(&x).unwrap()) + .unwrap() + .terms + .is_empty() + ); +} + +#[test] +fn checked_construction_and_comparison_keep_legacy_structure_semantics() { + let p: PauliString = "X".parse().unwrap(); + let raw = + Hamiltonian::from_list(vec![(p.clone(), 0.25.into()), (p.clone(), 0.75.into())]).unwrap(); + let canonical = Hamiltonian::from_terms(1, raw.terms.clone()).unwrap(); + assert_eq!(canonical, Hamiltonian::from_pauli(p)); + assert_ne!(raw, canonical); + assert!(raw.equiv(&canonical, 0.0).unwrap()); + assert_eq!((raw.clone() + canonical.clone()).terms.len(), 3); + assert_eq!(raw.try_add(&canonical).unwrap().terms.len(), 1); + assert_eq!(Hamiltonian::from_list(vec![]).unwrap().num_qubits, 0); + assert_eq!(Hamiltonian::from_terms(7, []).unwrap(), Hamiltonian::new(7)); + assert_eq!( + canonical.normalized().unwrap().normalized().unwrap(), + canonical + ); + let reversed = Hamiltonian::from_list(raw.terms.into_iter().rev().collect()).unwrap(); + assert_eq!(reversed.normalized().unwrap(), canonical); +} + +#[test] +fn explicit_chopping_follows_merging_and_preserves_tiny_coefficients() { + let tiny = f64::from_bits(1); + let p: PauliString = "Y".parse().unwrap(); + let mut phased = p.clone(); + phased.phase = Phase::I; + let small = Hamiltonian::from_terms(1, [(phased, tiny.into())]).unwrap(); + assert_eq!(small.terms[0].1, Complex64::new(0.0, tiny)); + for result in [ + small.try_mul(&Hamiltonian::identity(1)).unwrap(), + small.scaled(1.0.into()).unwrap(), + small.try_add(&Hamiltonian::new(1)).unwrap(), + small.adjoint().unwrap().adjoint().unwrap(), + ] { + assert_eq!(result, small); + } + let mut h = Hamiltonian::from_list(vec![(p.clone(), 0.75.into()), (p, 0.75.into())]).unwrap(); + h.chop(1.0).unwrap(); + assert_eq!(h.terms[0].1, Complex64::new(1.5, 0.0)); + h.chop(1.5).unwrap(); + assert_eq!(h, Hamiltonian::new(1)); + let mut small = small; + small.chop(0.0).unwrap(); + assert_eq!(small.terms.len(), 1); + small.chop(tiny).unwrap(); + assert!(small.terms.is_empty()); + let mut complex = + Hamiltonian::from_terms(1, [("X".parse().unwrap(), Complex64::new(3.0, 4.0))]).unwrap(); + complex.chop(4.0).unwrap(); + assert_eq!(complex.terms.len(), 1); + complex.chop(5.0).unwrap(); + assert!(complex.terms.is_empty()); +} + +#[test] +fn hermiticity_uses_adjoint_difference_tolerance_without_projection() { + let h = + Hamiltonian::from_terms(1, [("Z".parse().unwrap(), Complex64::new(1.0, 0.125))]).unwrap(); + assert!(h.is_hermitian(0.25).unwrap()); + assert!(!h.is_hermitian(0.249).unwrap()); + assert_eq!(h.terms[0].1.im, 0.125); + let phased = raw_sum(&[("X", Phase::I, Complex64::new(0.0, -1.0))]); + assert!(phased.is_hermitian(0.0).unwrap()); + assert!(!h.equiv(&Hamiltonian::identity(1), 0.0).unwrap()); +} + +#[test] +fn tensor_and_permutation_embedding_match_independent_matrices() { + let at = [("YX", Phase::MinusI, Complex64::new(0.5, 0.25))]; + let bt = [ + ("Z", Phase::I, Complex64::new(-0.25, 1.0)), + ("X", Phase::Minus, 0.5.into()), + ]; + let a = raw_sum(&at); + let b = raw_sum(&bt); + assert_matrix_close( + &a.tensor(&b).unwrap().to_matrix().unwrap(), + &matrix_tensor(&matrix_oracle(&at), &matrix_oracle(&bt)), + ); + let swapped = a.remap_qubits(&[1, 0], 2).unwrap(); + assert_matrix_close( + &swapped.to_matrix().unwrap(), + &matrix_oracle(&[("XY", Phase::MinusI, Complex64::new(0.5, 0.25))]), + ); + let embedded = a.remap_qubits(&[3, 1], 4).unwrap(); + assert_matrix_close( + &embedded.to_matrix().unwrap(), + &matrix_oracle(&[("XIYI", Phase::MinusI, Complex64::new(0.5, 0.25))]), + ); + let scalar = Hamiltonian::identity(0) + .scaled(Complex64::new(2.0, -0.5)) + .unwrap(); + assert_eq!( + a.tensor(&scalar).unwrap(), + a.scaled(Complex64::new(2.0, -0.5)).unwrap() + ); + assert_eq!( + scalar.tensor(&a).unwrap(), + a.scaled(Complex64::new(2.0, -0.5)).unwrap() + ); +} + +#[test] +fn zero_and_scalar_operators_retain_declared_spaces() { + for width in [0, 1, 128] { + let zero = Hamiltonian::new(width); + let identity = Hamiltonian::identity(width); + assert_eq!(zero.try_mul(&identity).unwrap(), zero); + assert_eq!(identity.try_mul(&zero).unwrap(), zero); + assert_eq!(identity.try_sub(&identity).unwrap(), zero); + assert_eq!(identity.scaled(0.0.into()).unwrap(), zero); + assert_eq!( + zero.tensor(&Hamiltonian::new(2)).unwrap().num_qubits, + width + 2 + ); + let map: Vec<_> = (0..width).map(|q| q + 1).collect(); + assert_eq!( + zero.remap_qubits(&map, width + 2).unwrap(), + Hamiltonian::new(width + 2) + ); + assert_eq!( + identity.remap_qubits(&map, width + 2).unwrap(), + Hamiltonian::identity(width + 2) + ); + } + assert_eq!( + Hamiltonian::identity(0).to_matrix().unwrap(), + arr2(&[[Complex64::new(1.0, 0.0)]]) + ); +} + +#[test] +fn wide_register_arithmetic_never_needs_machine_word_masks() { + use crate::qis::Pauli; + for width in [65, 128, 1000] { + let mut p = PauliString::new(width); + p.set_pauli(width - 1, Pauli::Y); + p.set_pauli(0, Pauli::Z); + let a = Hamiltonian::from_terms(width, [(p.clone(), 0.5.into())]).unwrap(); + assert_eq!( + a.try_mul(&a).unwrap(), + Hamiltonian::identity(width).scaled(0.25.into()).unwrap() + ); + assert!(a.is_hermitian(0.0).unwrap()); + assert!( + a.try_add(&a) + .unwrap() + .equiv(&a.scaled(2.0.into()).unwrap(), 0.0) + .unwrap() + ); + let mapping: Vec<_> = (0..width).rev().collect(); + let reversed = a.remap_qubits(&mapping, width).unwrap(); + assert_eq!(reversed.terms[0].0.get_pauli(0), Pauli::Y); + assert_eq!(reversed.terms[0].0.get_pauli(width - 1), Pauli::Z); + assert_eq!(reversed.remap_qubits(&mapping, width).unwrap(), a); + let tensor = a + .tensor(&Hamiltonian::from_pauli("X".parse().unwrap())) + .unwrap(); + assert_eq!(tensor.num_qubits, width + 1); + assert_eq!(tensor.terms[0].0.get_pauli(0), Pauli::X); + assert_eq!(tensor.terms[0].0.get_pauli(width), Pauli::Y); + } +} + +#[test] +fn invalid_inputs_are_rejected_even_when_other_operand_is_zero() { + let mut short = PauliString::new(1); + short.x.clear(); + let mut long = PauliString::new(1); + long.z.push(false); + for terms in [ + vec![(PauliString::new(2), 1.0.into())], + vec![(short, 1.0.into())], + vec![(long, 1.0.into())], + vec![(PauliString::new(1), f64::NAN.into())], + vec![(PauliString::new(1), f64::INFINITY.into())], + vec![(PauliString::new(1), Complex64::new(0.0, f64::NEG_INFINITY))], + ] { + let h = Hamiltonian { + num_qubits: 1, + terms: terms.clone(), + }; + let zero = Hamiltonian::new(1); + assert!(Hamiltonian::from_terms(1, terms).is_err()); + assert!(h.try_add(&zero).is_err()); + assert!(h.try_sub(&zero).is_err()); + assert!(h.try_mul(&zero).is_err()); + assert!(zero.try_mul(&h).is_err()); + assert!(h.scaled(0.0.into()).is_err()); + assert!(h.adjoint().is_err()); + assert!(h.tensor(&zero).is_err()); + assert!(zero.tensor(&h).is_err()); + assert!(h.remap_qubits(&[0], 1).is_err()); + assert!(h.equiv(&h, 0.0).is_err()); + assert!(h.is_hermitian(0.0).is_err()); + assert!(h.to_matrix().is_err()); + let mut chopped = h.clone(); + assert!(chopped.chop(0.0).is_err()); + // Compare coefficient bits because NaN is not equal to itself. + assert_eq!(chopped.num_qubits, h.num_qubits); + assert_eq!(chopped.terms.len(), h.terms.len()); + for ((actual_p, actual_c), (expected_p, expected_c)) in chopped.terms.iter().zip(&h.terms) { + assert_eq!(actual_p, expected_p); + assert_eq!(actual_c.re.to_bits(), expected_c.re.to_bits()); + assert_eq!(actual_c.im.to_bits(), expected_c.im.to_bits()); + } + } + let a = Hamiltonian::new(1); + let b = Hamiltonian::new(2); + for result in [a.try_add(&b), a.try_sub(&b), a.try_mul(&b)] { + assert!(matches!(result, Err(QisError::QubitMismatch { .. }))); + } + assert!(a.equiv(&b, 0.0).is_err()); +} + +#[test] +fn invalid_tolerances_mappings_and_scalars_do_not_mutate_input() { + let h = Hamiltonian::identity(2); + for atol in [-1.0, f64::NAN, f64::INFINITY] { + let mut chopped = h.clone(); + assert!(chopped.chop(atol).is_err()); + assert_eq!(chopped, h); + assert!(h.equiv(&h, atol).is_err()); + assert!(h.is_hermitian(atol).is_err()); + } + for mapping in [&[0][..], &[0, 0], &[0, 2]] { + assert!(h.remap_qubits(mapping, 2).is_err()); + assert!(Hamiltonian::new(2).remap_qubits(mapping, 2).is_err()); + } + for factor in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + assert!(Hamiltonian::new(2).scaled(factor.into()).is_err()); + } + assert!( + Hamiltonian::new(usize::MAX) + .tensor(&Hamiltonian::new(1)) + .is_err() + ); +} + +#[test] +fn unrepresentable_embeddings_return_errors_without_panicking() { + let limit = bitvec::slice::BitSlice::::MAX_BITS; + for width in [limit + 1, usize::MAX] { + // Empty source mapping is valid, but scalar identity still requires a + // target Pauli string: reject its unrepresentable width before allocation. + let scalar = Hamiltonian::identity(0); + assert!(matches!( + scalar.remap_qubits(&[], width), + Err(QisError::UnsupportedOperation(_)) + )); + assert!(matches!( + Hamiltonian::identity(1).remap_qubits(&[width - 1], width), + Err(QisError::UnsupportedOperation(_)) + )); + // Zero sums do not allocate target bit vectors and retain declared width. + assert_eq!( + Hamiltonian::new(0).remap_qubits(&[], width).unwrap(), + Hamiltonian::new(width) + ); + assert_eq!( + Hamiltonian::new(width).tensor(&scalar).unwrap(), + Hamiltonian::new(width) + ); + } +} + +#[test] +fn intermediate_and_dense_coefficient_overflow_is_reported() { + let max = Hamiltonian::identity(1).scaled(f64::MAX.into()).unwrap(); + let two = Hamiltonian::identity(1).scaled(2.0.into()).unwrap(); + for result in [ + max.try_add(&max), + max.scaled(2.0.into()), + max.try_mul(&two), + max.tensor(&two), + max.try_sub(&max.scaled((-1.0).into()).unwrap()), + ] { + assert!(matches!(result, Err(QisError::NonFiniteCoefficient { .. }))); + } + // A later cancellation cannot hide an earlier nonfinite accumulation. + let raw = Hamiltonian::from_list( + [f64::MAX, f64::MAX, -f64::MAX] + .into_iter() + .map(|c| (PauliString::new(1), c.into())) + .collect(), + ) + .unwrap(); + assert!(matches!( + raw.normalized(), + Err(QisError::NonFiniteCoefficient { .. }) + )); + let mut chopped = raw.clone(); + assert!(chopped.chop(0.0).is_err()); + assert_eq!(chopped, raw); + let dense = Hamiltonian::from_terms( + 1, + [ + ("I".parse().unwrap(), f64::MAX.into()), + ("Z".parse().unwrap(), f64::MAX.into()), + ], + ) + .unwrap(); + assert!(matches!( + dense.to_matrix(), + Err(QisError::NonFiniteCoefficient { .. }) + )); +} + +#[test] +fn dense_conversion_checks_shift_element_and_byte_overflow_before_allocation() { + // On 64-bit: 64 overflows the shift, 32 the element count, 30 the byte range. + for width in [ + usize::BITS as usize, + usize::BITS as usize / 2, + (usize::BITS as usize - 4) / 2, + usize::MAX, + ] { + assert!(matches!( + Hamiltonian::new(width).to_matrix(), + Err(QisError::UnsupportedOperation(_)) + )); + } +} + +#[test] +fn mapped_fermionic_products_and_adjoint_use_public_pauli_algebra() { + use crate::qis::{FermionToQubitMapper, FermionicOp, JordanWignerMapper}; + let mapper = JordanWignerMapper::new(); + for p in 0..3 { + for q in 0..3 { + let a = FermionicOp::creation(3, p).unwrap(); + let b = FermionicOp::annihilation(3, q).unwrap(); + let mapped_a = mapper.map_operator(&a).unwrap(); + let mapped_b = mapper.map_operator(&b).unwrap(); + assert!( + mapped_a + .try_mul(&mapped_b) + .unwrap() + .equiv(&mapper.map_operator(&a.try_mul(&b).unwrap()).unwrap(), 0.0) + .unwrap() + ); + assert!( + mapped_a + .adjoint() + .unwrap() + .equiv(&mapper.map_operator(&a.adjoint()).unwrap(), 0.0) + .unwrap() + ); + } + } +} + +#[test] +fn hermitian_normalization_projects_only_accepted_imaginary_residuals() { + let h = Hamiltonian::from_list(vec![ + ("I".parse().unwrap(), Complex64::new(0.0, 1e-12)), + ("Z".parse().unwrap(), Complex64::new(1e-16, -1e-10)), + ]) + .unwrap(); + let normalized = h.normalized_hermitian().unwrap(); + assert_eq!(normalized.num_qubits, 1); + assert_eq!( + normalized.terms, + vec![("Z".parse().unwrap(), Complex64::new(1e-16, 0.0))] + ); + assert_eq!(normalized.normalized_hermitian().unwrap(), normalized); + // General complex normalization must not apply the real projection. + assert_eq!(h.normalized().unwrap().terms.len(), 2); + + let mut invalid = h.clone(); + invalid.terms[0].1.im = 1.01e-10; + assert!(matches!( + invalid.normalized_hermitian(), + Err(QisError::NotHermitian) + )); + + // Validate the merged imaginary coefficient before removing zero real parts. + let merged_invalid = Hamiltonian::from_list(vec![ + ("Z".parse().unwrap(), Complex64::new(0.0, 0.75e-10)), + ("Z".parse().unwrap(), Complex64::new(0.0, 0.75e-10)), + ]) + .unwrap(); + assert!(matches!( + merged_invalid.normalized_hermitian(), + Err(QisError::NotHermitian) + )); +} + #[test] fn empty_hamiltonian_to_matrix_is_zero() { assert_eq!( diff --git a/crates/cqlib-core/src/qis/mod.rs b/crates/cqlib-core/src/qis/mod.rs index cf196fb3..45906459 100644 --- a/crates/cqlib-core/src/qis/mod.rs +++ b/crates/cqlib-core/src/qis/mod.rs @@ -24,6 +24,7 @@ //! - [`state`]: Quantum state representations (statevector, density matrix, stabilizer) //! - [`pauli`]: Pauli operators and Pauli strings with symplectic encoding //! - [`hamiltonian`]: Hamiltonian construction from Pauli strings +//! - [`fermion`]: Fermionic operator algebra and fermion-to-qubit mappings //! - [`observable`]: Trait for computing expectation values //! - [`entropy`]: Entropy measures and entanglement metrics //! - [`error`]: Error types for QIS operations @@ -79,6 +80,7 @@ pub mod entropy; pub mod error; pub mod evolution; +pub mod fermion; pub mod hamiltonian; pub mod metrics; pub mod observable; @@ -88,6 +90,9 @@ pub mod state; pub use error::{PauliStringParseError, QisError}; pub use evolution::{PauliEvolution, TrotterMode}; +pub use fermion::{ + FermionToQubitMapper, FermionicLadder, FermionicOp, JordanWignerMapper, OccupationStateMapper, +}; pub use hamiltonian::Hamiltonian; pub use observable::Observable; pub use pauli::{Pauli, PauliIter, PauliString, Phase}; diff --git a/crates/cqlib-core/src/qis/observable.rs b/crates/cqlib-core/src/qis/observable.rs index 26b8712d..ce1733e5 100644 --- a/crates/cqlib-core/src/qis/observable.rs +++ b/crates/cqlib-core/src/qis/observable.rs @@ -76,6 +76,9 @@ const VARIANCE_TOLERANCE: f64 = 1e-10; /// /// Methods may return [`QisError::QubitMismatch`] if the observable /// and the quantum state have incompatible qubit counts. +/// Real expectation methods return [`QisError::NotHermitian`] for non-Hermitian +/// observables. Nonfinite Hamiltonian coefficients, including merge overflow, +/// return [`QisError::InvalidParameterValue`]. pub trait Observable { /// Computes the expectation value for a statevector: $\langle\psi|O|\psi\rangle$. /// @@ -183,6 +186,16 @@ fn finalize_variance(variance: f64) -> Result { } } +// Keep the existing Observable error contract while sharing algebraic validation. +fn normalized_observable(h: &Hamiltonian) -> Result { + h.normalized_hermitian().map_err(|error| match error { + nonfinite @ QisError::NonFiniteCoefficient { .. } => { + QisError::InvalidParameterValue(nonfinite.to_string()) + } + other => other, + }) +} + impl Observable for Hamiltonian { fn expectation_statevector(&self, sv: &Statevector) -> Result { if sv.num_qubits != self.num_qubits { @@ -192,10 +205,11 @@ impl Observable for Hamiltonian { }); } + let normalized = normalized_observable(self)?; let mut expected_value = 0.0; // Iterate over each term in the Hamiltonian - for (pauli_str, coeff) in &self.terms { + for (pauli_str, coeff) in &normalized.terms { let x_mask = pauli_str.x_mask(); let z_mask = pauli_str.z_mask(); @@ -240,11 +254,12 @@ impl Observable for Hamiltonian { }); } + let normalized = normalized_observable(self)?; let mut expected_value = 0.0; let n = self.num_qubits; let dim = 1 << n; // 2^n - for (pauli_str, coeff) in &self.terms { + for (pauli_str, coeff) in &normalized.terms { let x_mask = pauli_str.x_mask(); let z_mask = pauli_str.z_mask(); @@ -286,9 +301,10 @@ impl Observable for Hamiltonian { &self, measurements: &[(PauliString, HashMap)], ) -> Result { + let normalized = normalized_observable(self)?; let mut expected_value = 0.0; - for (term_pauli, coeff) in &self.terms { + for (term_pauli, coeff) in &normalized.terms { let term_x_mask = term_pauli.x_mask(); let term_z_mask = term_pauli.z_mask(); let p_active = term_x_mask | term_z_mask; @@ -368,8 +384,7 @@ impl Observable for Hamiltonian { }); } - let mut simplified = self.clone(); - simplified.simplify(); + let mut simplified = normalized_observable(self)?; for (_, coeff) in &mut simplified.terms { if coeff.im.abs() > VARIANCE_TOLERANCE { @@ -401,6 +416,7 @@ impl Observable for PauliString { }); } + self.ensure_hermitian()?; let x_mask = self.x_mask(); let z_mask = self.z_mask(); let y_phase = self.y_phase(); @@ -433,6 +449,7 @@ impl Observable for PauliString { }); } + self.ensure_hermitian()?; let n = self.num_qubits; let dim = 1 << n; let x_mask = self.x_mask(); @@ -461,6 +478,7 @@ impl Observable for PauliString { &self, measurements: &[(PauliString, HashMap)], ) -> Result { + self.ensure_hermitian()?; let term_x_mask = self.x_mask(); let term_z_mask = self.z_mask(); let p_active = term_x_mask | term_z_mask; diff --git a/crates/cqlib-core/src/qis/observable_test.rs b/crates/cqlib-core/src/qis/observable_test.rs index 1fc05c34..4b5b4e03 100644 --- a/crates/cqlib-core/src/qis/observable_test.rs +++ b/crates/cqlib-core/src/qis/observable_test.rs @@ -390,3 +390,162 @@ fn test_empty_hamiltonian_variance_is_zero() { fn test_variance_tiny_negative_roundoff_clamps_to_zero() { assert_close(finalize_variance(-VARIANCE_TOLERANCE / 2.0).unwrap(), 0.0); } + +#[test] +fn nonhermitian_observables_are_rejected_even_at_zero_expectation() { + let sv = Statevector::new(1); + let dm = DensityMatrix::new(1); + let probs = HashMap::from([("0".to_string(), 1.0)]); + for label in ["iZ", "-iI", "iX"] { + let p: PauliString = label.parse().unwrap(); + let h = Hamiltonian::from_pauli(p.clone()); + let measurements = vec![(p.clone(), probs.clone())]; + for obs in [&p as &dyn Observable, &h as &dyn Observable] { + assert!(matches!( + obs.expectation_statevector(&sv), + Err(QisError::NotHermitian) + )); + assert!(matches!( + obs.expectation_density_matrix(&dm), + Err(QisError::NotHermitian) + )); + assert!(matches!( + obs.expectation_probs(&measurements), + Err(QisError::NotHermitian) + )); + } + assert!(matches!(p.expectation(&probs), Err(QisError::NotHermitian))); + } +} + +#[test] +fn hermiticity_is_checked_after_phase_and_duplicate_merging() { + let sv = Statevector::new(1); + let dm = DensityMatrix::new(1); + let probs = vec![( + "Z".parse().unwrap(), + HashMap::from([("0".to_string(), 1.0)]), + )]; + for terms in [ + vec![("iZ", Complex64::new(0.0, -1.0))], + vec![ + ("Z", Complex64::new(1.0, 2.0)), + ("Z", Complex64::new(0.0, -2.0)), + ], + vec![("Z", Complex64::new(1e-11, 0.0))], + ] { + let h = Hamiltonian::from_list( + terms + .iter() + .map(|(p, c)| (p.parse().unwrap(), *c)) + .collect(), + ) + .unwrap(); + let expected = if terms[0].1.re == 1e-11 { 1e-11 } else { 1.0 }; + for actual in [ + h.expectation_statevector(&sv).unwrap(), + h.expectation_density_matrix(&dm).unwrap(), + h.expectation_probs(&probs).unwrap(), + ] { + assert!((actual - expected).abs() < 1e-14); + } + } + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + let h = + Hamiltonian::from_list(vec![("Z".parse().unwrap(), Complex64::new(bad, 0.0))]).unwrap(); + assert!(matches!( + h.expectation_statevector(&sv), + Err(QisError::InvalidParameterValue(_)) + )); + assert!(matches!( + h.expectation_density_matrix(&dm), + Err(QisError::InvalidParameterValue(_)) + )); + assert!(matches!( + h.expectation_probs(&probs), + Err(QisError::InvalidParameterValue(_)) + )); + } + let h = Hamiltonian::from_pauli("iZZ".parse().unwrap()); + assert!(matches!( + h.expectation_statevector(&sv), + Err(QisError::QubitMismatch { .. }) + )); +} + +#[test] +fn hermiticity_tolerance_and_merged_overflow() { + for (imaginary, valid) in [(0.5e-10, true), (2e-10, false)] { + let h = + Hamiltonian::from_list(vec![("Z".parse().unwrap(), Complex64::new(1.0, imaginary))]) + .unwrap(); + assert_eq!( + h.expectation_statevector(&Statevector::new(1)).is_ok(), + valid + ); + assert_eq!( + h.expectation_density_matrix(&DensityMatrix::new(1)).is_ok(), + valid + ); + } + let h = Hamiltonian::from_list(vec![ + ("Z".parse().unwrap(), Complex64::new(f64::MAX, 0.0)); + 2 + ]) + .unwrap(); + assert!(matches!( + h.expectation_statevector(&Statevector::new(1)), + Err(QisError::InvalidParameterValue(_)) + )); +} + +#[test] +fn variance_validates_coefficients_before_merging_and_retains_small_terms() { + let sv = Statevector::new(1); + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + for coeff in [Complex64::new(bad, 0.0), Complex64::new(0.0, bad)] { + let h = Hamiltonian::from_list(vec![("Z".parse().unwrap(), coeff)]).unwrap(); + assert!(matches!( + h.variance_statevector(&sv), + Err(QisError::InvalidParameterValue(_)) + )); + } + } + let h = Hamiltonian::from_list(vec![ + ("Z".parse().unwrap(), Complex64::new(f64::MAX, 0.0)); + 2 + ]) + .unwrap(); + assert!(matches!( + h.variance_statevector(&sv), + Err(QisError::InvalidParameterValue(_)) + )); + for terms in [ + vec![("iX", Complex64::new(0.0, -1.0))], + vec![ + ("X", Complex64::new(1.0, 2.0)), + ("X", Complex64::new(0.0, -2.0)), + ], + ] { + let h = Hamiltonian::from_list( + terms + .into_iter() + .map(|(p, c)| (p.parse().unwrap(), c)) + .collect(), + ) + .unwrap(); + assert!((h.variance_statevector(&sv).unwrap() - 1.0).abs() < 1e-12); + } + let h = + Hamiltonian::from_list(vec![("X".parse().unwrap(), Complex64::new(1e-11, 0.0))]).unwrap(); + assert!((h.variance_statevector(&sv).unwrap() - 1e-22).abs() < 1e-34); + let invalid = Hamiltonian::from_pauli("iZ".parse().unwrap()); + assert!(matches!( + invalid.variance_statevector(&sv), + Err(QisError::NotHermitian) + )); + assert!(matches!( + invalid.variance_statevector(&Statevector::new(2)), + Err(QisError::QubitMismatch { .. }) + )); +} diff --git a/crates/cqlib-core/src/qis/pauli.rs b/crates/cqlib-core/src/qis/pauli.rs index 543efb97..12a8a5c1 100644 --- a/crates/cqlib-core/src/qis/pauli.rs +++ b/crates/cqlib-core/src/qis/pauli.rs @@ -859,10 +859,12 @@ impl PauliString { /// let exp = ps.expectation(&probs).unwrap(); /// assert!((exp).abs() < 1e-10); /// ``` + /// Returns `QisError::NotHermitian` for an imaginary Pauli phase. pub fn expectation( &self, probs: &std::collections::HashMap, ) -> Result { + self.ensure_hermitian()?; // Check if this Pauli string contains X or Y operators // X is represented by x[i]=1, z[i]=0 // Y is represented by x[i]=1, z[i]=1 @@ -914,6 +916,13 @@ impl PauliString { Ok((exp_value * global_phase).re) } + pub(crate) fn ensure_hermitian(&self) -> Result<(), crate::qis::error::QisError> { + match self.phase { + Phase::Plus | Phase::Minus => Ok(()), + Phase::I | Phase::MinusI => Err(crate::qis::error::QisError::NotHermitian), + } + } + /// Computes the phase exponent for multiplying two Pauli operators. /// /// Returns the exponent `n` such that `P1 * P2 = i^n * P3`. diff --git a/crates/cqlib-core/src/qis/state/aligned_buffer.rs b/crates/cqlib-core/src/qis/state/aligned_buffer.rs index 7784083e..608f5d52 100644 --- a/crates/cqlib-core/src/qis/state/aligned_buffer.rs +++ b/crates/cqlib-core/src/qis/state/aligned_buffer.rs @@ -61,6 +61,15 @@ impl AlignedBuffer { AlignedBuffer { ptr, len, layout } } + /// Fallible allocation used by checked state constructors. + pub(super) fn try_new_zeroed(len: usize) -> Option { + let size = len.checked_mul(size_of::())?; + let layout = Layout::from_size_align(size.max(1), 64.max(align_of::())).ok()?; + // SAFETY: layout is nonzero and validated; null is returned as failure. + let ptr = NonNull::new(unsafe { alloc_zeroed(layout) } as *mut T)?; + Some(Self { ptr, len, layout }) + } + /// Returns the raw pointer to the first element (64-byte aligned). #[allow(dead_code)] #[inline(always)] diff --git a/crates/cqlib-core/src/qis/state/density_matrix.rs b/crates/cqlib-core/src/qis/state/density_matrix.rs index b3560659..904e9f9a 100644 --- a/crates/cqlib-core/src/qis/state/density_matrix.rs +++ b/crates/cqlib-core/src/qis/state/density_matrix.rs @@ -151,7 +151,7 @@ impl DensityMatrix { Ok(()) } - /// Validates that two qubit indices are within bounds. + /// Validates that two qubit indices are within bounds and distinct. #[inline] fn validate_two_qubits(&self, q0: usize, q1: usize) -> Result<(), QisError> { if self.num_qubits == 0 { @@ -171,10 +171,15 @@ impl DensityMatrix { max: self.num_qubits.saturating_sub(1), }); } + if q0 == q1 { + return Err(QisError::InvalidParameterValue(format!( + "Duplicate qubit index {q0} in gate operation" + ))); + } Ok(()) } - /// Validates that all qubit indices in a slice are within bounds. + /// Validates that all qubit indices in a slice are within bounds and distinct. #[inline] fn validate_qubits(&self, qubits: &[usize]) -> Result<(), QisError> { if self.num_qubits == 0 { @@ -190,6 +195,13 @@ impl DensityMatrix { }); } } + for (i, &q) in qubits.iter().enumerate() { + if qubits[..i].contains(&q) { + return Err(QisError::InvalidParameterValue(format!( + "Duplicate qubit index {q} in gate operation" + ))); + } + } Ok(()) } @@ -197,17 +209,35 @@ impl DensityMatrix { /// /// # Arguments /// * `num_qubits` - Number of qubits in the system. + /// + /// # Panics + /// + /// Panics if the dimension is unrepresentable or allocation fails. + /// Use [`Self::try_new`] to receive an error instead. pub fn new(num_qubits: usize) -> Self { - let size = 1 << (2 * num_qubits); - let mut data = vec![Complex64::new(0.0, 0.0); size]; - if size > 0 { - data[0] = Complex64::new(1.0, 0.0); - } - Self { + Self::try_new(num_qubits).expect("cannot allocate density matrix") + } + + /// Creates the ground state, returning an error for an unrepresentable + /// dimension or a failed allocation. + /// + /// # Errors + /// + /// Returns [`QisError::InvalidParameterValue`] for an unrepresentable + /// dimension, or [`QisError::UnsupportedOperation`] if allocation fails. + pub fn try_new(num_qubits: usize) -> Result { + let size = super::checked_state_len(num_qubits, true)?; + let mut data = Vec::new(); + data.try_reserve_exact(size).map_err(|_| { + QisError::UnsupportedOperation("density matrix allocation failed".into()) + })?; + data.resize(size, Complex64::new(0.0, 0.0)); + data[0] = Complex64::new(1.0, 0.0); + Ok(Self { data, num_qubits, qubit_map: None, - } + }) } /// Creates the maximally mixed state $I / 2^N$. @@ -218,18 +248,29 @@ impl DensityMatrix { /// /// Like every dense density-matrix constructor, this allocates $O(4^N)$ /// complex values. + /// + /// # Panics + /// + /// Panics if the dimension is unrepresentable or allocation fails. + /// Use [`Self::try_maximally_mixed`] to receive an error instead. pub fn maximally_mixed(num_qubits: usize) -> Self { - let dim = 1 << num_qubits; - let mut data = vec![Complex64::new(0.0, 0.0); dim * dim]; + Self::try_maximally_mixed(num_qubits).expect("cannot allocate density matrix") + } + + /// Fallible variant of [`Self::maximally_mixed`]. + /// + /// # Errors + /// + /// Returns [`QisError::InvalidParameterValue`] for an unrepresentable + /// dimension, or [`QisError::UnsupportedOperation`] if allocation fails. + pub fn try_maximally_mixed(num_qubits: usize) -> Result { + let mut state = Self::try_new(num_qubits)?; + let dim = 1usize << num_qubits; let probability = Complex64::new(1.0 / dim as f64, 0.0); for index in 0..dim { - data[index * dim + index] = probability; - } - Self { - data, - num_qubits, - qubit_map: None, + state.data[index * dim + index] = probability; } + Ok(state) } /// Creates a density matrix from an initial statevector (pure state). @@ -244,17 +285,17 @@ impl DensityMatrix { /// Returns [`QisError::InvalidStateDimension`] if the `initial_state` length is /// incorrect, or [`QisError::NotNormalized`] if it is not normalized. pub fn from_state(num_qubits: usize, initial_state: Vec) -> Result { - let dim = 1 << num_qubits; + super::checked_state_len(num_qubits, true)?; + let dim = 1usize << num_qubits; if initial_state.len() != dim { return Err(QisError::InvalidStateDimension(initial_state.len())); } let norm: f64 = initial_state.iter().map(|c| c.norm_sqr()).sum(); - if (norm - 1.0).abs() >= 1e-10 { + if !norm.is_finite() || (norm - 1.0).abs() >= 1e-10 { return Err(QisError::NotNormalized); } - let size = 1 << (2 * num_qubits); - let mut data = vec![Complex64::new(0.0, 0.0); size]; + let mut data = Self::try_new(num_qubits)?.data; let kernel = |(i, chunk): (usize, &mut [Complex64])| { let alpha_i = initial_state[i]; @@ -293,7 +334,7 @@ impl DensityMatrix { num_qubits: usize, dm_state: Vec, ) -> Result { - let size = 1 << (2 * num_qubits); + let size = super::checked_state_len(num_qubits, true)?; if dm_state.len() != size { return Err(QisError::InvalidStateDimension(dm_state.len())); } @@ -337,7 +378,7 @@ impl DensityMatrix { /// * `Ok(DensityMatrix)` - The resulting density matrix after execution. /// * `Err(QisError)` - If the circuit contains unsupported operations. pub fn from_circuit(circuit: &Circuit) -> Result { - let mut dm = DensityMatrix::new(circuit.num_qubits()); + let mut dm = DensityMatrix::try_new(circuit.num_qubits())?; dm.apply_circuit(circuit)?; Ok(dm) } @@ -435,30 +476,31 @@ impl DensityMatrix { let num_controls = mc_gate.num_ctrl_qubits(); let base_gate = mc_gate.base_gate(); - if num_controls == 1 { - let control = qubit_indices[0]; - let target = qubit_indices[1]; - match base_gate { - StandardGate::X => dm.apply_cx(control, target)?, - StandardGate::Y => dm.apply_cy(control, target)?, - StandardGate::Z => dm.apply_cz(control, target)?, - StandardGate::RX => dm.apply_crx(control, target, params[0])?, - StandardGate::RY => dm.apply_cry(control, target, params[0])?, - StandardGate::RZ => dm.apply_crz(control, target, params[0])?, - _ => { - let matrix = mc_gate.matrix(¶ms).map_err(|_| { - QisError::CircuitError(CircuitError::NoMatrixRepresentation) - })?; - dm.apply_unitary_gate(&qubit_indices, &matrix)?; - } + match (num_controls, *base_gate) { + (0, StandardGate::GPhase) => { + dm.apply_standard_gate(*base_gate, &qubit_indices, ¶ms)? + } + (1, StandardGate::X) => dm.apply_cx(qubit_indices[0], qubit_indices[1])?, + (1, StandardGate::Y) => dm.apply_cy(qubit_indices[0], qubit_indices[1])?, + (1, StandardGate::Z) => dm.apply_cz(qubit_indices[0], qubit_indices[1])?, + (1, StandardGate::RX) => { + dm.apply_crx(qubit_indices[0], qubit_indices[1], params[0])? + } + (1, StandardGate::RY) => { + dm.apply_cry(qubit_indices[0], qubit_indices[1], params[0])? + } + (1, StandardGate::RZ) => { + dm.apply_crz(qubit_indices[0], qubit_indices[1], params[0])? + } + (2, StandardGate::X) => { + dm.apply_ccx(qubit_indices[0], qubit_indices[1], qubit_indices[2])? + } + _ => { + let matrix = mc_gate.matrix(¶ms).map_err(|_| { + QisError::CircuitError(CircuitError::NoMatrixRepresentation) + })?; + dm.apply_unitary_gate(&qubit_indices, &matrix)?; } - } else if num_controls == 2 && *base_gate == StandardGate::X { - dm.apply_ccx(qubit_indices[0], qubit_indices[1], qubit_indices[2])?; - } else { - let matrix = mc_gate.matrix(¶ms).map_err(|_| { - QisError::CircuitError(CircuitError::NoMatrixRepresentation) - })?; - dm.apply_unitary_gate(&qubit_indices, &matrix)?; } } Instruction::UnitaryGate(u_gate) => { @@ -573,13 +615,25 @@ impl DensityMatrix { /// /// # Arguments /// * `num_qubits` - Number of qubits in the system. + /// + /// # Panics + /// + /// Panics if the dimension is unrepresentable or allocation fails. + /// Use [`Self::try_zeros`] to receive an error instead. pub fn zeros(num_qubits: usize) -> Self { - let size = 1 << (2 * num_qubits); - Self { - data: vec![Complex64::new(0.0, 0.0); size], - num_qubits, - qubit_map: None, - } + Self::try_zeros(num_qubits).expect("cannot allocate density matrix") + } + + /// Fallible variant of [`Self::zeros`]. + /// + /// # Errors + /// + /// Returns [`QisError::InvalidParameterValue`] for an unrepresentable + /// dimension, or [`QisError::UnsupportedOperation`] if allocation fails. + pub fn try_zeros(num_qubits: usize) -> Result { + let mut state = Self::try_new(num_qubits)?; + state.data[0] = Complex64::new(0.0, 0.0); + Ok(state) } /// Computes the trace of the density matrix. @@ -611,6 +665,13 @@ impl DensityMatrix { /// # Returns /// `true` if the matrix is Hermitian within the specified tolerance. pub fn is_hermitian(&self, tol: f64) -> bool { + if self + .data + .iter() + .any(|v| !v.re.is_finite() || !v.im.is_finite()) + { + return false; + } let dim = 1 << self.num_qubits; for i in 0..dim { for j in 0..i { diff --git a/crates/cqlib-core/src/qis/state/density_matrix_noise.rs b/crates/cqlib-core/src/qis/state/density_matrix_noise.rs index 7e0d41b1..6aff31b0 100644 --- a/crates/cqlib-core/src/qis/state/density_matrix_noise.rs +++ b/crates/cqlib-core/src/qis/state/density_matrix_noise.rs @@ -92,11 +92,26 @@ impl DensityMatrixNoise { /// // Simulator with empty noise model /// let sim = DensityMatrixNoise::new(2, Some(cqlib_core::device::NoiseModel::new())); /// ``` + /// + /// # Panics + /// + /// Panics if the dimension is unrepresentable or allocation fails. + /// Use [`Self::try_new`] to receive an error instead. pub fn new(num_qubits: usize, noise_model: Option) -> Self { - Self { - state: DensityMatrix::new(num_qubits), + Self::try_new(num_qubits, noise_model).expect("cannot allocate noisy density matrix") + } + + /// Fallible ground-state constructor, preserving the supplied noise model. + /// + /// # Errors + /// + /// Returns [`QisError::InvalidParameterValue`] for an unrepresentable + /// dimension, or [`QisError::UnsupportedOperation`] if allocation fails. + pub fn try_new(num_qubits: usize, noise_model: Option) -> Result { + Ok(Self { + state: DensityMatrix::try_new(num_qubits)?, noise_model, - } + }) } /// Simulates a circuit, applying noise after each operation. @@ -139,7 +154,7 @@ impl DensityMatrixNoise { noise_model: Option, ) -> Result { let mut dms = Self { - state: DensityMatrix::new(circuit.num_qubits()), + state: DensityMatrix::try_new(circuit.num_qubits())?, noise_model, }; dms.apply_circuit(circuit)?; @@ -199,51 +214,64 @@ impl DensityMatrixNoise { .map(|p| p.evaluate(&None).ok()) .collect(); - for op in circuit.operations() { - let params: Vec = op - .params - .iter() - .map(|p| match p { - CircuitParam::Fixed(v) => Ok(*v), - CircuitParam::Index(idx) => parameter_values - .get(*idx as usize) - .copied() - .flatten() - .ok_or(QisError::CircuitError( - crate::circuit::CircuitError::SymbolicParameterError, - )), - }) - .collect::, QisError>>()?; - - let qs: Result, QisError> = op - .qubits - .iter() - .map(|q| { - qubit_map.get(q).copied().ok_or_else(|| { - QisError::CircuitError(crate::circuit::CircuitError::QubitNotFound(q.id())) + // Expose labels to gate-noise lookup during execution, restoring the + // previous binding on error (already executed gates are not rolled back). + let previous_map = sim.state.qubit_map.replace(qubit_map); + let result = (|| { + for op in circuit.operations() { + let params: Vec = op + .params + .iter() + .map(|p| match p { + CircuitParam::Fixed(v) => Ok(*v), + CircuitParam::Index(idx) => parameter_values + .get(*idx as usize) + .copied() + .flatten() + .ok_or(QisError::CircuitError( + crate::circuit::CircuitError::SymbolicParameterError, + )), + }) + .collect::, QisError>>()?; + + let qs: Result, QisError> = op + .qubits + .iter() + .map(|q| { + sim.state + .qubit_map + .as_ref() + .unwrap() + .get(q) + .copied() + .ok_or_else(|| { + QisError::CircuitError(crate::circuit::CircuitError::QubitNotFound( + q.id(), + )) + }) }) - }) - .collect(); - let qs = qs?; + .collect(); + let qs = qs?; - match &op.instruction { - Instruction::Standard(gate) => { - sim.apply_standard_gate_noise(*gate, &qs, ¶ms)?; - } - Instruction::McGate(mc_gate) => { - let num_controls = mc_gate.num_ctrl_qubits(); - let base_gate = mc_gate.base_gate(); - - if num_controls == 1 { - let c = qs[0]; - let t = qs[1]; - match base_gate { - StandardGate::X => sim.apply_cx(c, t)?, - StandardGate::Y => sim.apply_cy(c, t)?, - StandardGate::Z => sim.apply_cz(c, t)?, - StandardGate::RX => sim.apply_crx(c, t, params[0])?, - StandardGate::RY => sim.apply_cry(c, t, params[0])?, - StandardGate::RZ => sim.apply_crz(c, t, params[0])?, + match &op.instruction { + Instruction::Standard(gate) => { + sim.apply_standard_gate_noise(*gate, &qs, ¶ms)?; + } + Instruction::McGate(mc_gate) => { + let num_controls = mc_gate.num_ctrl_qubits(); + let base_gate = mc_gate.base_gate(); + + match (num_controls, *base_gate) { + (0, StandardGate::GPhase) => { + sim.apply_standard_gate_noise(*base_gate, &qs, ¶ms)? + } + (1, StandardGate::X) => sim.apply_cx(qs[0], qs[1])?, + (1, StandardGate::Y) => sim.apply_cy(qs[0], qs[1])?, + (1, StandardGate::Z) => sim.apply_cz(qs[0], qs[1])?, + (1, StandardGate::RX) => sim.apply_crx(qs[0], qs[1], params[0])?, + (1, StandardGate::RY) => sim.apply_cry(qs[0], qs[1], params[0])?, + (1, StandardGate::RZ) => sim.apply_crz(qs[0], qs[1], params[0])?, + (2, StandardGate::X) => sim.apply_ccx(qs[0], qs[1], qs[2])?, _ => { let matrix = mc_gate.matrix(¶ms).map_err(|_| { QisError::CircuitError( @@ -254,59 +282,52 @@ impl DensityMatrixNoise { sim.apply_noise(*base_gate, &qs)?; } } - } else if num_controls == 2 && *base_gate == StandardGate::X { - sim.apply_ccx(qs[0], qs[1], qs[2])?; - } else { - let matrix = mc_gate.matrix(¶ms).map_err(|_| { - QisError::CircuitError( + } + Instruction::UnitaryGate(u_gate) => { + if let Some(matrix) = u_gate.matrix() { + sim.apply_unitary_gate(&qs, matrix)?; + sim.apply_noise(StandardGate::U, &qs)?; + } else { + return Err(QisError::CircuitError( crate::circuit::CircuitError::NoMatrixRepresentation, - ) - })?; - sim.apply_unitary_gate(&qs, &matrix)?; - sim.apply_noise(*base_gate, &qs)?; + )); + } } - } - Instruction::UnitaryGate(u_gate) => { - if let Some(matrix) = u_gate.matrix() { - sim.apply_unitary_gate(&qs, matrix)?; - sim.apply_noise(StandardGate::U, &qs)?; - } else { + Instruction::CircuitGate(_) => { return Err(QisError::CircuitError( - crate::circuit::CircuitError::NoMatrixRepresentation, + crate::circuit::CircuitError::InvalidOperation( + "CircuitGate should have been decomposed".to_string(), + ), )); } - } - Instruction::CircuitGate(_) => { - return Err(QisError::CircuitError( - crate::circuit::CircuitError::InvalidOperation( - "CircuitGate should have been decomposed".to_string(), - ), - )); - } - Instruction::Directive(directive) => match directive { - Directive::Barrier => {} - Directive::Measure => { - return Err(QisError::UnsupportedOperation( + Instruction::Directive(directive) => match directive { + Directive::Barrier => {} + Directive::Measure => { + return Err(QisError::UnsupportedOperation( "legacy Measure directive is not supported by noisy density matrix circuit evolution; use Circuit::measure as an output declaration".to_string(), )); - } - Directive::Reset => { - let qubit = qs[0]; - sim.reset(qubit)?; - } - }, - Instruction::Delay => continue, - Instruction::ClassicalControl(_) => { - return Err(QisError::UnsupportedOperation( + } + Directive::Reset => { + let qubit = qs[0]; + sim.reset(qubit)?; + } + }, + Instruction::Delay => continue, + Instruction::ClassicalControl(_) => { + return Err(QisError::UnsupportedOperation( "classical control flow is not supported in noisy density matrix simulation" .to_string(), )); + } + Instruction::ClassicalData(_) => {} } - Instruction::ClassicalData(_) => {} } + Ok(()) + })(); + if result.is_err() { + sim.state.qubit_map = previous_map; } - sim.state.qubit_map = Some(qubit_map); - Ok(()) + result } /// Applies a standard gate and then applies any matching gate noise. @@ -342,7 +363,15 @@ impl DensityMatrixNoise { ))); } match gate { - StandardGate::I => {} + StandardGate::I => { + if qs[0] >= self.state.num_qubits { + return Err(QisError::IndexOutOfBounds { + index: qs[0], + max: self.state.num_qubits.saturating_sub(1), + }); + } + self.apply_noise(StandardGate::I, qs)?; + } StandardGate::X => self.apply_x(qs[0])?, StandardGate::Y => self.apply_y(qs[0])?, StandardGate::Z => self.apply_z(qs[0])?, @@ -393,6 +422,19 @@ impl DensityMatrixNoise { .collect() } + /// Resolves a storage position to its noise-model qubit ID. + /// Callers validate positions before looking up noise. + fn noise_qubit(&self, position: usize) -> Qubit { + self.state + .qubit_map + .as_ref() + .and_then(|map| { + map.iter() + .find_map(|(&qubit, &index)| (index == position).then_some(qubit)) + }) + .unwrap_or_else(|| Qubit::new(position as u32)) + } + /// Applies noise channels associated with a gate operation. /// /// Looks up the noise model for errors associated with `gate` on `qubits`, @@ -401,7 +443,7 @@ impl DensityMatrixNoise { fn apply_noise(&mut self, gate: StandardGate, qubits: &[usize]) -> Result<(), QisError> { if let Some(noise_model) = &self.noise_model { if qubits.len() == 1 { - let q0 = Qubit::new(qubits[0] as u32); + let q0 = self.noise_qubit(qubits[0]); let key = OperationKey::new_single(gate, q0); if let Some(errors) = noise_model.get_single_qubit_errors(&key) { for error in errors { @@ -411,8 +453,8 @@ impl DensityMatrixNoise { } } } else if qubits.len() == 2 { - let q0 = Qubit::new(qubits[0] as u32); - let q1 = Qubit::new(qubits[1] as u32); + let q0 = self.noise_qubit(qubits[0]); + let q1 = self.noise_qubit(qubits[1]); if let Ok(key) = OperationKey::new_double(gate, q0, q1) && let Some(errors) = noise_model.get_two_qubit_errors(&key) { @@ -423,9 +465,9 @@ impl DensityMatrixNoise { } } } else if qubits.len() == 3 { - let q0 = Qubit::new(qubits[0] as u32); - let q1 = Qubit::new(qubits[1] as u32); - let q2 = Qubit::new(qubits[2] as u32); + let q0 = self.noise_qubit(qubits[0]); + let q1 = self.noise_qubit(qubits[1]); + let q2 = self.noise_qubit(qubits[2]); if let Ok(_key) = OperationKey::new_triple(gate, q0, q1, q2) { // Current noise model struct doesn't have `get_three_qubit_errors`. // Ready for future extension without silently failing or panicking. @@ -993,12 +1035,21 @@ impl DensityMatrixNoise { /// /// # Arguments /// - /// * `qubits` - Indices of qubits to measure. + /// * `qubits` - Storage positions on which to apply readout errors, not circuit + /// qubit IDs. For a circuit-bound state, each position selects the noise + /// configured for `circuit.qubits()[position]`. Unbound states use identity IDs. /// /// # Returns /// /// A vector of probabilities for all 2^n computational basis states, where n - /// is the total number of qubits in the simulator. + /// is the total number of qubits in the simulator. The array retains storage + /// order regardless of the order or number of selected positions. An empty + /// selection returns the probabilities before readout noise. + /// + /// # Errors + /// + /// Returns [`QisError::IndexOutOfBounds`] for a position outside `0..num_qubits`, + /// including when no noise model is configured. /// /// # Examples /// @@ -1014,10 +1065,20 @@ impl DensityMatrixNoise { /// // For Bell state |Φ+⟩, P(|00⟩) ≈ 0.5 and P(|11⟩) ≈ 0.5 /// ``` pub fn probabilities_with_readout(&self, qubits: &[usize]) -> Result, QisError> { + for &position in qubits { + if position >= self.state.num_qubits { + return Err(QisError::IndexOutOfBounds { + index: position, + max: self.state.num_qubits.saturating_sub(1), + }); + } + } let mut probs = self.probabilities(); self.apply_readout_noise( &mut probs, - qubits.iter().map(|&q| (Qubit::new(q as u32), q)), + qubits + .iter() + .map(|&position| (self.noise_qubit(position), position)), )?; Ok(probs) } diff --git a/crates/cqlib-core/src/qis/state/density_matrix_noise_test.rs b/crates/cqlib-core/src/qis/state/density_matrix_noise_test.rs index 9c0bbfa9..3c8a055d 100644 --- a/crates/cqlib-core/src/qis/state/density_matrix_noise_test.rs +++ b/crates/cqlib-core/src/qis/state/density_matrix_noise_test.rs @@ -19,6 +19,37 @@ use ndarray::array; use num_complex::Complex64; use std::f64::consts::PI; +#[test] +fn duplicate_targets_leave_noisy_density_matrix_unchanged() { + let mut model = NoiseModel::new(); + model + .add_two_qubit_error( + StandardGate::CX, + Qubit::new(0), + Qubit::new(2), + TwoQubitNoise::CorrelatedPauli { + op_q0: Pauli::X, + op_q1: Pauli::X, + p: 0.2, + }, + ) + .unwrap(); + let mut initial = DensityMatrixNoise::new(3, Some(model)); + initial.apply_h(0).unwrap(); + initial.apply_s(0).unwrap(); + for gate in [StandardGate::CX, StandardGate::CZ] { + for q in 0..3 { + let mut sim = initial.clone(); + assert!(matches!( + sim.apply_standard_gate_noise(gate, &[q, q], &[]), + Err(QisError::InvalidParameterValue(msg)) + if msg.contains(&format!("Duplicate qubit index {q} ")) + )); + assert_eq!(sim.state.data(), initial.state.data()); + } + } +} + #[test] fn test_bit_flip_noise() { let mut noise_model = NoiseModel::new(); @@ -1176,6 +1207,146 @@ fn test_native_gates_amplitude_damping() { assert!(probs[0] > 0.0); } +#[test] +fn test_readout_uses_circuit_ids_at_selected_storage_positions() { + use crate::device::Outcome; + + for ids in [[0, 1, 2], [2, 0, 1], [2, 5, 9], [9, 2, 5]] { + for basis in 0..8 { + for (noise_position, &noise_id) in ids.iter().enumerate() { + let mut circuit = + Circuit::from_qubits(ids.iter().copied().map(Qubit::new).collect()).unwrap(); + for (position, &id) in ids.iter().enumerate() { + if basis & (1 << position) != 0 { + circuit.x(Qubit::new(id)).unwrap(); + } + } + let receipt = circuit.measure(Qubit::new(noise_id)).unwrap(); + let mut model = NoiseModel::new(); + model + .add_readout_error( + Qubit::new(noise_id), + ReadoutError { + p_0_given_1: 0.2, + p_1_given_0: 0.7, + }, + ) + .unwrap(); + let sim = DensityMatrixNoise::from_circuit(&circuit, Some(model)).unwrap(); + let original = sim.state.data().to_vec(); + let bit = (basis >> noise_position) & 1; + let flip_probability = if bit == 0 { 0.7 } else { 0.2 }; + + for selection in 0..8 { + let positions: Vec<_> = (0..3) + .rev() + .filter(|&position| selection & (1 << position) != 0) + .collect(); + let mut expected = [0.0; 8]; + expected[basis] = 1.0; + if selection & (1 << noise_position) != 0 { + expected[basis] = 1.0 - flip_probability; + expected[basis ^ (1 << noise_position)] = flip_probability; + } + let actual = sim.probabilities_with_readout(&positions).unwrap(); + assert_eq!(actual.len(), expected.len()); + for (actual, expected) in actual.iter().zip(&expected) { + assert!( + (actual - expected).abs() < 1e-12, + "IDs={ids:?}, basis={basis}, noise_position={noise_position}, positions={positions:?}: {actual} != {expected}" + ); + } + } + + let marginal = sim.probs_with_readout(&receipt).unwrap(); + let p_one = if bit == 0 { 0.7 } else { 0.8 }; + assert!((marginal[&Outcome::from_bitstring("1").unwrap()] - p_one).abs() < 1e-12); + assert_eq!(sim.state.data(), original.as_slice()); + } + } + } +} + +#[test] +fn test_readout_combines_mapped_errors_without_reordering_full_probabilities() { + use crate::device::Outcome; + + let mut circuit = + Circuit::from_qubits(vec![Qubit::new(9), Qubit::new(2), Qubit::new(5)]).unwrap(); + circuit.x(Qubit::new(9)).unwrap(); + let receipt = circuit + .measure_bits([Qubit::new(2), Qubit::new(9)]) + .unwrap(); + let mut model = NoiseModel::new(); + for (id, p_0_given_1, p_1_given_0) in [(9, 0.1, 0.2), (2, 0.3, 0.4)] { + model + .add_readout_error( + Qubit::new(id), + ReadoutError { + p_0_given_1, + p_1_given_0, + }, + ) + .unwrap(); + } + let sim = DensityMatrixNoise::from_circuit(&circuit, Some(model)).unwrap(); + let expected = [0.06, 0.54, 0.04, 0.36, 0.0, 0.0, 0.0, 0.0]; + for positions in [&[0, 1][..], &[1, 0], &[2, 1, 0]] { + let actual = sim.probabilities_with_readout(positions).unwrap(); + assert_eq!(actual.len(), expected.len()); + for (actual, expected) in actual.iter().zip(expected) { + assert!((actual - expected).abs() < 1e-12); + } + } + let marginal = sim.probs_with_readout(&receipt).unwrap(); + for (bits, probability) in [("00", 0.06), ("10", 0.54), ("01", 0.04), ("11", 0.36)] { + assert!((marginal[&Outcome::from_bitstring(bits).unwrap()] - probability).abs() < 1e-12); + } + assert_eq!( + sim.probabilities(), + vec![0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + ); +} + +#[test] +fn test_readout_validates_positions_independently_of_noise_model() { + let mut model = NoiseModel::new(); + model + .add_readout_error( + Qubit::new(9), + ReadoutError { + p_0_given_1: 0.0, + p_1_given_0: 1.0, + }, + ) + .unwrap(); + for noise_model in [None, Some(NoiseModel::new()), Some(model)] { + for bound in [false, true] { + let mut sim = DensityMatrixNoise::new(2, noise_model.clone()); + if bound { + let circuit = Circuit::from_qubits(vec![Qubit::new(9), Qubit::new(2)]).unwrap(); + sim.apply_circuit(&circuit).unwrap(); + } + for index in [2, 9, usize::MAX] { + assert!(matches!( + sim.probabilities_with_readout(&[0, index]), + Err(QisError::IndexOutOfBounds { index: actual, max: 1 }) if actual == index + )); + } + assert_eq!( + sim.probabilities_with_readout(&[]).unwrap(), + sim.probabilities() + ); + } + let sim = DensityMatrixNoise::new(0, noise_model); + assert_eq!(sim.probabilities_with_readout(&[]).unwrap(), vec![1.0]); + assert!(matches!( + sim.probabilities_with_readout(&[0]), + Err(QisError::IndexOutOfBounds { index: 0, max: 0 }) + )); + } +} + #[test] fn test_apply_readout_noise_out_of_bounds() { let mut sim = DensityMatrixNoise::new(2, Some(NoiseModel::new())); @@ -1459,3 +1630,288 @@ fn test_ccx_with_noise_model_does_not_panic() { "CCX should produce support on |111>, got {probs:?}" ); } + +#[test] +fn pauli_probability_boundary_preserves_simulation_trace() { + let noise = SingleQubitNoise::Pauli { + px: 0.3, + py: 0.6, + pz: 0.1, + }; + let mut model = NoiseModel::new(); + model + .add_single_qubit_error(StandardGate::X, Qubit::new(0), noise) + .unwrap(); + let mut sim = DensityMatrixNoise::new(1, Some(model)); + sim.apply_x(0).unwrap(); + assert!((sim.probabilities()[0] - 0.9).abs() < 1e-12); + assert!((sim.probabilities().iter().sum::() - 1.0).abs() < 1e-12); +} + +#[test] +fn gate_noise_uses_original_labels_and_operand_order() { + for ids in [[0, 1], [5, 12], [12, 5]] { + let qs = ids.map(Qubit::new); + let mut circuit = Circuit::from_qubits(qs.to_vec()).unwrap(); + circuit.x(qs[0]).unwrap(); + let mut model = NoiseModel::new(); + model + .add_single_qubit_error(StandardGate::X, qs[0], SingleQubitNoise::BitFlip(1.0)) + .unwrap(); + let mut sim = DensityMatrixNoise::from_circuit(&circuit, Some(model)).unwrap(); + assert!((sim.probabilities()[0] - 1.0).abs() < 1e-12); + sim.apply_x(0).unwrap(); + assert!((sim.probabilities()[0] - 1.0).abs() < 1e-12); + for reverse in [false, true] { + let mut circuit = Circuit::from_qubits(qs.to_vec()).unwrap(); + let [control, target] = if reverse { [qs[1], qs[0]] } else { qs }; + circuit.cx(control, target).unwrap(); + let mut model = NoiseModel::new(); + model + .add_two_qubit_error( + StandardGate::CX, + control, + target, + TwoQubitNoise::Independent { + q0_noise: SingleQubitNoise::BitFlip(1.0), + q1_noise: SingleQubitNoise::BitFlip(0.0), + }, + ) + .unwrap(); + let sim = DensityMatrixNoise::from_circuit(&circuit, Some(model)).unwrap(); + let expected = if reverse { 2 } else { 1 }; + assert!((sim.probabilities()[expected] - 1.0).abs() < 1e-12); + } + } +} + +#[test] +fn failed_noisy_circuit_preserves_label_binding() { + use crate::circuit::Parameter; + let q = Qubit::new(5); + let mut bad = Circuit::from_qubits(vec![q]).unwrap(); + bad.x(q).unwrap(); + bad.rz(q, Parameter::symbol("unbound")).unwrap(); + let mut model = NoiseModel::new(); + model + .add_single_qubit_error(StandardGate::X, q, SingleQubitNoise::BitFlip(1.0)) + .unwrap(); + let mut sim = DensityMatrixNoise::new(1, Some(model.clone())); + assert!(sim.apply_circuit(&bad).is_err()); + // Completed gates used label 5, but the failed application did not bind it. + assert!((sim.probabilities()[0] - 1.0).abs() < 1e-12); + sim.apply_circuit(&Circuit::new(1)).unwrap(); + + let mut good = Circuit::from_qubits(vec![q]).unwrap(); + good.x(q).unwrap(); + let mut bound = DensityMatrixNoise::from_circuit(&good, Some(model)).unwrap(); + assert!(bound.apply_circuit(&bad).is_err()); + bound.apply_x(0).unwrap(); + assert!((bound.probabilities()[0] - 1.0).abs() < 1e-12); + assert!(bound.apply_circuit(&Circuit::new(1)).is_err()); +} + +#[test] +fn identity_noise_respects_labels_and_repetition() { + for ids in [[0, 1], [12, 5]] { + for p in [0.0, 0.25, 1.0] { + for count in [1, 2, 3] { + let qs = ids.map(Qubit::new); + let mut c = Circuit::from_qubits(qs.to_vec()).unwrap(); + for _ in 0..count { + c.i(qs[1]).unwrap(); + } + let mut model = NoiseModel::new(); + model + .add_single_qubit_error(StandardGate::I, qs[1], SingleQubitNoise::BitFlip(p)) + .unwrap(); + let sim = DensityMatrixNoise::from_circuit(&c, Some(model)).unwrap(); + let flipped = (1.0 - (1.0 - 2.0 * p).powi(count)) / 2.0; + for (actual, expected) in + sim.probabilities() + .iter() + .zip([1.0 - flipped, 0.0, flipped, 0.0]) + { + assert!((actual - expected).abs() < 1e-12); + } + assert_eq!( + DensityMatrixNoise::from_circuit(&c, None) + .unwrap() + .probabilities(), + vec![1.0, 0.0, 0.0, 0.0] + ); + } + } + } + let mut sim = DensityMatrixNoise::new(1, None); + assert!( + sim.apply_standard_gate_noise(StandardGate::I, &[1], &[]) + .is_err() + ); +} + +#[test] +fn controlled_gphase_circuit_evolution() { + for ids in [[0, 1, 2], [12, 5, 31]] { + let qubits = ids.map(Qubit::new); + for controls in [ + vec![qubits[2]], + vec![qubits[2], qubits[0]], + vec![qubits[0], qubits[2]], + ] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut preparation = Circuit::from_qubits(qubits.to_vec()).unwrap(); + for qubit in qubits { + preparation.h(qubit).unwrap(); + } + preparation.s(qubits[1]).unwrap(); + let mut phase = Circuit::from_qubits(qubits.to_vec()).unwrap(); + phase + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [theta.into()], + ) + .unwrap(); + let mut circuit = preparation.clone(); + circuit + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [theta.into()], + ) + .unwrap(); + let mask = controls.iter().fold(0usize, |mask, q| { + mask | (1 << qubits.iter().position(|candidate| candidate == q).unwrap()) + }); + let expected: Vec = (0..8) + .map(|index| { + let amplitude = if index & 2 == 0 { + Complex64::new(1.0, 0.0) + } else { + Complex64::new(0.0, 1.0) + } / 8.0_f64.sqrt(); + if index & mask == mask { + amplitude * Complex64::from_polar(1.0, theta) + } else { + amplitude + } + }) + .collect(); + let expected_data = expected + .iter() + .flat_map(|a| expected.iter().map(move |b| a * b.conj())) + .collect::>(); + let actual = DensityMatrixNoise::from_circuit(&circuit, None).unwrap(); + let mut incremental = DensityMatrixNoise::new(3, None); + incremental.apply_circuit(&preparation).unwrap(); + incremental.apply_circuit(&phase).unwrap(); + for values in [actual.state.data(), incremental.state.data()] { + for (actual, expected) in values.iter().zip(&expected_data) { + assert!( + (actual - expected).norm() < 1e-12, + "{actual:?} != {expected:?}" + ); + } + } + let mut inverse = Circuit::from_qubits(qubits.to_vec()).unwrap(); + inverse + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [(-theta).into()], + ) + .unwrap(); + incremental.apply_circuit(&inverse).unwrap(); + let baseline = DensityMatrixNoise::from_circuit(&preparation, None).unwrap(); + for (actual, expected) in incremental.state.data().iter().zip(baseline.state.data()) + { + assert!((actual - expected).norm() < 1e-12); + } + } + } + } +} + +#[test] +fn controlled_gphase_noise_applies_after_unitary_once() { + let qubits = [Qubit::new(12), Qubit::new(5)]; + let mut circuit = Circuit::from_qubits(qubits.to_vec()).unwrap(); + circuit.x(qubits[0]).unwrap(); + circuit.h(qubits[1]).unwrap(); + circuit + .multi_control( + StandardGate::GPhase, + [qubits[1]], + Vec::::new(), + [0.37.into()], + ) + .unwrap(); + let mut model = NoiseModel::new(); + model + .add_single_qubit_error( + StandardGate::GPhase, + qubits[1], + SingleQubitNoise::BitFlip(0.23), + ) + .unwrap(); + model + .add_single_qubit_error( + StandardGate::GPhase, + qubits[0], + SingleQubitNoise::BitFlip(1.0), + ) + .unwrap(); + let sim = DensityMatrixNoise::from_circuit(&circuit, Some(model)).unwrap(); + let amplitudes = [ + Complex64::new(0.0, 0.0), + Complex64::new(1.0, 0.0) / 2.0_f64.sqrt(), + Complex64::new(0.0, 0.0), + Complex64::from_polar(1.0 / 2.0_f64.sqrt(), 0.37), + ]; + for row in 0..4 { + for col in 0..4 { + let expected = 0.77 * amplitudes[row] * amplitudes[col].conj() + + 0.23 * amplitudes[row ^ 2] * amplitudes[col ^ 2].conj(); + assert!((sim.state.data()[row * 4 + col] - expected).norm() < 1e-12); + } + } +} + +#[test] +fn zero_control_gphase_circuit_evolution() { + use crate::circuit::gate::{Instruction, MCGate}; + for num_qubits in [0, 1, 3] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut circuit = Circuit::new(num_qubits); + if num_qubits > 0 { + circuit.h(Qubit::new(0)).unwrap(); + } + circuit + .append( + Instruction::McGate(Box::new(MCGate::new(0, StandardGate::GPhase))), + Vec::::new(), + [theta.into()], + None, + ) + .unwrap(); + let actual = DensityMatrixNoise::from_circuit(&circuit, None).unwrap(); + let mut amplitudes = vec![Complex64::new(0.0, 0.0); 1 << num_qubits]; + amplitudes[0] = Complex64::from_polar(1.0, theta); + if num_qubits > 0 { + amplitudes[0] /= 2.0_f64.sqrt(); + amplitudes[1] = amplitudes[0]; + } + let expected = amplitudes + .iter() + .flat_map(|a| amplitudes.iter().map(move |b| a * b.conj())) + .collect::>(); + for (actual, expected) in actual.state.data().iter().zip(&expected) { + assert!((actual - expected).norm() < 1e-12); + } + } + } +} diff --git a/crates/cqlib-core/src/qis/state/density_matrix_test.rs b/crates/cqlib-core/src/qis/state/density_matrix_test.rs index 34bc2572..95e89ce8 100644 --- a/crates/cqlib-core/src/qis/state/density_matrix_test.rs +++ b/crates/cqlib-core/src/qis/state/density_matrix_test.rs @@ -408,6 +408,98 @@ fn test_zeros_and_add_assign() { assert_relative_eq!(dm1.probabilities()[1], 0.5); } +#[test] +fn duplicate_two_qubit_targets_leave_density_matrix_unchanged() { + let mut initial = DensityMatrix::new(3); + initial.apply_h(0).unwrap(); + initial.apply_ry(1, 0.37).unwrap(); + initial.apply_s(0).unwrap(); + for gate in [ + StandardGate::CX, + StandardGate::CZ, + StandardGate::CY, + StandardGate::SWAP, + StandardGate::RXX, + StandardGate::RYY, + StandardGate::RZZ, + StandardGate::RZX, + StandardGate::CRX, + StandardGate::CRY, + StandardGate::CRZ, + StandardGate::FSIM, + ] { + for q in 0..3 { + let mut dm = initial.clone(); + let result = dm.apply_standard_gate(gate, &[q, q], &vec![0.37; gate.num_params()]); + assert!(matches!(result, Err(QisError::InvalidParameterValue(msg)) + if msg.contains(&format!("Duplicate qubit index {q} ")))); + assert_eq!(dm.data(), initial.data(), "{gate:?} on [{q}, {q}]"); + } + } + for targets in [[0, 0, 2], [0, 2, 0], [2, 0, 0]] { + let mut dm = initial.clone(); + assert!(matches!( + dm.apply_ccx(targets[0], targets[1], targets[2]), + Err(QisError::InvalidParameterValue(msg)) if msg.contains("Duplicate qubit index 0 ") + )); + assert_eq!(dm.data(), initial.data()); + } +} + +#[test] +fn duplicate_custom_gate_targets_leave_density_matrix_unchanged() { + let mut dm = DensityMatrix::new(3); + dm.apply_h(0).unwrap(); + dm.apply_s(0).unwrap(); + let before = dm.data().to_vec(); + let matrix = StandardGate::CX.matrix(&[]).unwrap(); + let matrix = std::array::from_fn(|r| std::array::from_fn(|c| matrix[[r, c]])); + for q in 0..3 { + assert!(matches!( + dm.apply_two_qubit_gate(q, q, matrix), + Err(QisError::InvalidParameterValue(msg)) + if msg.contains(&format!("Duplicate qubit index {q} ")) + )); + assert_eq!(dm.data(), before); + } +} + +#[test] +fn duplicate_kraus_targets_leave_density_matrix_unchanged() { + let amplitudes: Vec<_> = (1..=8) + .map(|i| Complex64::new(i as f64 / 204.0_f64.sqrt(), 0.0)) + .collect(); + let initial = DensityMatrix::from_state(3, amplitudes).unwrap(); + for (targets, duplicate) in [ + (&[0, 0][..], 0), + (&[1, 1][..], 1), + (&[2, 2][..], 2), + (&[0, 2, 0][..], 0), + (&[0, 0, 2][..], 0), + (&[2, 0, 0][..], 0), + ] { + let dim = 1 << targets.len(); + let norm: f64 = (1..=dim).map(|i| (i * i) as f64).sum(); + let operator = (0..dim) + .flat_map(|r| { + (0..dim).map(move |c| { + Complex64::new( + if r == c { 1.0 } else { 0.0 } - 2.0 * ((r + 1) * (c + 1)) as f64 / norm, + 0.0, + ) + }) + }) + .collect(); + let mut dm = initial.clone(); + assert!(matches!( + dm.apply_kraus(&[operator], targets), + Err(QisError::InvalidParameterValue(msg)) + if msg.contains(&format!("Duplicate qubit index {duplicate} ")) + )); + assert_eq!(dm.data(), initial.data()); + } +} + #[test] fn test_single_qubit_gates() { let mut dm = DensityMatrix::new(1); @@ -1226,3 +1318,137 @@ fn test_psd_inf_rejected() { }; assert!(!dm.is_positive_semidefinite_approx(1e-10)); } + +#[test] +fn hermiticity_rejects_nonfinite_entries() { + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] { + for index in 0..4 { + for value in [Complex64::new(bad, 0.0), Complex64::new(0.0, bad)] { + let mut dm = DensityMatrix::new(1); + dm.data[index] = value; + assert!(!dm.is_hermitian(1e-10)); + assert!(dm.validate_physical(1e-10).is_err()); + } + } + } +} + +#[test] +fn controlled_gphase_circuit_evolution() { + for ids in [[0, 1, 2], [12, 5, 31]] { + let qubits = ids.map(Qubit::new); + for controls in [ + vec![qubits[2]], + vec![qubits[2], qubits[0]], + vec![qubits[0], qubits[2]], + ] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut preparation = Circuit::from_qubits(qubits.to_vec()).unwrap(); + for qubit in qubits { + preparation.h(qubit).unwrap(); + } + preparation.s(qubits[1]).unwrap(); + let mut phase = Circuit::from_qubits(qubits.to_vec()).unwrap(); + phase + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [theta.into()], + ) + .unwrap(); + let mut circuit = preparation.clone(); + circuit + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [theta.into()], + ) + .unwrap(); + let mask = controls.iter().fold(0usize, |mask, q| { + mask | (1 << qubits.iter().position(|candidate| candidate == q).unwrap()) + }); + let expected: Vec = (0..8) + .map(|index| { + let amplitude = if index & 2 == 0 { + Complex64::new(1.0, 0.0) + } else { + Complex64::new(0.0, 1.0) + } / 8.0_f64.sqrt(); + if index & mask == mask { + amplitude * Complex64::from_polar(1.0, theta) + } else { + amplitude + } + }) + .collect(); + let expected_data = expected + .iter() + .flat_map(|a| expected.iter().map(move |b| a * b.conj())) + .collect::>(); + let actual = DensityMatrix::from_circuit(&circuit).unwrap(); + let mut incremental = DensityMatrix::new(3); + incremental.apply_circuit(&preparation).unwrap(); + incremental.apply_circuit(&phase).unwrap(); + for values in [actual.data(), incremental.data()] { + for (actual, expected) in values.iter().zip(&expected_data) { + assert!( + (actual - expected).norm() < 1e-12, + "{actual:?} != {expected:?}" + ); + } + } + let mut inverse = Circuit::from_qubits(qubits.to_vec()).unwrap(); + inverse + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [(-theta).into()], + ) + .unwrap(); + incremental.apply_circuit(&inverse).unwrap(); + let baseline = DensityMatrix::from_circuit(&preparation).unwrap(); + for (actual, expected) in incremental.data().iter().zip(baseline.data()) { + assert!((actual - expected).norm() < 1e-12); + } + } + } + } +} + +#[test] +fn zero_control_gphase_circuit_evolution() { + use crate::circuit::gate::{Instruction, MCGate}; + for num_qubits in [0, 1, 3] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut circuit = Circuit::new(num_qubits); + if num_qubits > 0 { + circuit.h(Qubit::new(0)).unwrap(); + } + circuit + .append( + Instruction::McGate(Box::new(MCGate::new(0, StandardGate::GPhase))), + Vec::::new(), + [theta.into()], + None, + ) + .unwrap(); + let actual = DensityMatrix::from_circuit(&circuit).unwrap(); + let mut amplitudes = vec![Complex64::new(0.0, 0.0); 1 << num_qubits]; + amplitudes[0] = Complex64::from_polar(1.0, theta); + if num_qubits > 0 { + amplitudes[0] /= 2.0_f64.sqrt(); + amplitudes[1] = amplitudes[0]; + } + let expected = amplitudes + .iter() + .flat_map(|a| amplitudes.iter().map(move |b| a * b.conj())) + .collect::>(); + for (actual, expected) in actual.data().iter().zip(&expected) { + assert!((actual - expected).norm() < 1e-12); + } + } + } +} diff --git a/crates/cqlib-core/src/qis/state/mod.rs b/crates/cqlib-core/src/qis/state/mod.rs index f5216562..6c23a9a2 100644 --- a/crates/cqlib-core/src/qis/state/mod.rs +++ b/crates/cqlib-core/src/qis/state/mod.rs @@ -172,3 +172,19 @@ pub use statevector::Statevector; #[cfg(test)] #[path = "state_test.rs"] mod state_test; + +// Validate both the exponent and allocation layout before shifting or allocating. +fn checked_state_len(num_qubits: usize, density: bool) -> Result { + let invalid = || { + QisError::InvalidParameterValue(format!( + "state dimension is too large for {num_qubits} qubits" + )) + }; + let exponent = num_qubits + .checked_mul(if density { 2 } else { 1 }) + .ok_or_else(invalid)?; + let exponent = u32::try_from(exponent).map_err(|_| invalid())?; + let len = 1usize.checked_shl(exponent).ok_or_else(invalid)?; + std::alloc::Layout::array::(len).map_err(|_| invalid())?; + Ok(len) +} diff --git a/crates/cqlib-core/src/qis/state/stabilizer.rs b/crates/cqlib-core/src/qis/state/stabilizer.rs index c62ec501..01cc7430 100644 --- a/crates/cqlib-core/src/qis/state/stabilizer.rs +++ b/crates/cqlib-core/src/qis/state/stabilizer.rs @@ -914,9 +914,9 @@ impl StabilizerState { /// Applies the √Y gate (Y2P, SY, Ry(π/2)) to qubit `qubit`. /// - /// Conjugation: X→Z, Y→Y, Z→−X. + /// Conjugation U P U†: X→−Z, Y→Y, Z→X. /// Rule per row `i`: - /// - `phase[i] ^= 2 * (!x[i][qubit] & z[i][qubit])` (flip for Z→−X) + /// - `phase[i] ^= 2 * (x[i][qubit] & !z[i][qubit])` (flip for X→−Z) /// - swap `x[i][qubit]` ↔ `z[i][qubit]` pub fn apply_y2p(&mut self, qubit: usize) -> Result<(), QisError> { self.validate_qubit(qubit)?; @@ -927,7 +927,7 @@ impl StabilizerState { let base = row * 2 * rl; let x = (self.tableau[base + word] & mask) != 0; let z = (self.tableau[base + rl + word] & mask) != 0; - if !x && z { + if x && !z { self.phases[row] ^= 2; } // swap x ↔ z @@ -947,9 +947,9 @@ impl StabilizerState { /// Applies the √Y† gate (Y2M, SYdg, Ry(−π/2)) to qubit `qubit`. /// - /// Conjugation: X→−Z, Y→Y, Z→X. + /// Conjugation U P U†: X→Z, Y→Y, Z→−X. /// Rule per row `i`: - /// - `phase[i] ^= 2 * (x[i][qubit] & !z[i][qubit])` (flip for X→−Z) + /// - `phase[i] ^= 2 * (!x[i][qubit] & z[i][qubit])` (flip for Z→−X) /// - swap `x[i][qubit]` ↔ `z[i][qubit]` pub fn apply_y2m(&mut self, qubit: usize) -> Result<(), QisError> { self.validate_qubit(qubit)?; @@ -960,7 +960,7 @@ impl StabilizerState { let base = row * 2 * rl; let x = (self.tableau[base + word] & mask) != 0; let z = (self.tableau[base + rl + word] & mask) != 0; - if x && !z { + if !x && z { self.phases[row] ^= 2; } // swap x ↔ z @@ -1662,20 +1662,16 @@ impl StabilizerState { Instruction::Standard(gate) => { state.apply_clifford_gate(*gate, &qubit_indices, ¶ms)?; } - Instruction::McGate(mc) if mc.num_ctrl_qubits() == 1 => { - let ctrl = qubit_indices[0]; - let tgt = qubit_indices[1]; - match mc.base_gate() { - StandardGate::X => state.apply_cx(ctrl, tgt)?, - StandardGate::Y => state.apply_cy(ctrl, tgt)?, - StandardGate::Z => state.apply_cz(ctrl, tgt)?, - g => { - return Err(QisError::UnsupportedOperation(format!( - "Controlled-{g} is not a Clifford gate" - ))); - } + Instruction::McGate(mc) if mc.num_ctrl_qubits() == 1 => match mc.base_gate() { + StandardGate::X => state.apply_cx(qubit_indices[0], qubit_indices[1])?, + StandardGate::Y => state.apply_cy(qubit_indices[0], qubit_indices[1])?, + StandardGate::Z => state.apply_cz(qubit_indices[0], qubit_indices[1])?, + g => { + return Err(QisError::UnsupportedOperation(format!( + "Controlled-{g} is not supported in stabilizer simulation" + ))); } - } + }, Instruction::McGate(mc) => { return Err(QisError::UnsupportedOperation(format!( "{}-controlled gates are not supported in stabilizer simulation", diff --git a/crates/cqlib-core/src/qis/state/stabilizer_test.rs b/crates/cqlib-core/src/qis/state/stabilizer_test.rs index 2633a1d2..8a3381a0 100644 --- a/crates/cqlib-core/src/qis/state/stabilizer_test.rs +++ b/crates/cqlib-core/src/qis/state/stabilizer_test.rs @@ -11,6 +11,228 @@ // that they have been altered from the originals. use super::*; +use crate::qis::{Hamiltonian, Statevector}; + +const CLIFFORD_GATES: [StandardGate; 15] = [ + StandardGate::I, + StandardGate::H, + StandardGate::X, + StandardGate::Y, + StandardGate::Z, + StandardGate::S, + StandardGate::SDG, + StandardGate::X2P, + StandardGate::X2M, + StandardGate::Y2P, + StandardGate::Y2M, + StandardGate::CX, + StandardGate::CY, + StandardGate::CZ, + StandardGate::SWAP, +]; + +#[test] +fn test_clifford_gates_on_complete_pauli_product_eigenstates() { + // These six states span the one-qubit operator space. Check every Pauli + // observable so opposite rotations cannot hide behind equal Z probabilities. + let preparations: [&[StandardGate]; 6] = [ + &[], + &[StandardGate::X], + &[StandardGate::H], + &[StandardGate::H, StandardGate::Z], + &[StandardGate::H, StandardGate::S], + &[StandardGate::H, StandardGate::Z, StandardGate::S], + ]; + for gate in CLIFFORD_GATES { + let n = gate.num_qubits(); + let qubits: Vec<_> = (0..n).collect(); + for input in 0..6usize.pow(n as u32) { + let mut state = StabilizerState::new(n); + let mut reference = Statevector::new(n); + let mut digits = input; + for q in 0..n { + for &prep in preparations[digits % 6] { + state.apply_standard_gate(prep, &[q], &[]).unwrap(); + reference + .apply_unitary_gate(&[q], &prep.matrix(&[]).unwrap()) + .unwrap(); + } + digits /= 6; + } + state.apply_standard_gate(gate, &qubits, &[]).unwrap(); + reference + .apply_unitary_gate(&qubits, &gate.matrix(&[]).unwrap()) + .unwrap(); + for mut index in 0..4usize.pow(n as u32) { + let mut pauli = PauliString::new(n); + for q in 0..n { + pauli.set_pauli(q, [Pauli::I, Pauli::X, Pauli::Y, Pauli::Z][index % 4]); + index /= 4; + } + let expected = reference + .expectation(&Hamiltonian::from_pauli(pauli.clone())) + .unwrap(); + let actual = state.pauli_expectation(&pauli).unwrap(); + assert!( + (actual as f64 - expected).abs() < 1e-10, + "gate={gate:?}, input={input}, observable={pauli}: {actual} != {expected}" + ); + } + } + } +} + +#[test] +fn test_y2_rotations_match_h_z_decompositions_across_word_boundaries() { + // Compare both stabilizer and destabilizer rows, including untouched bits + // on either side of a packed-word boundary and rows containing Y. + let mut initial = StabilizerState::new(66); + initial.apply_h(0).unwrap(); + for q in 1..66 { + initial.apply_cx(q - 1, q).unwrap(); + initial.apply_s(q).unwrap(); + } + for q in [0, 63, 64, 65] { + for gate in [StandardGate::Y2P, StandardGate::Y2M] { + let mut actual = initial.clone(); + actual.apply_standard_gate(gate, &[q], &[]).unwrap(); + let mut expected = initial.clone(); + // In execution order: Y2P = Z;H, Y2M = H;Z. + if gate == StandardGate::Y2P { + expected.apply_z(q).unwrap(); + expected.apply_h(q).unwrap(); + } else { + expected.apply_h(q).unwrap(); + expected.apply_z(q).unwrap(); + } + assert_eq!(&*actual.tableau, &*expected.tableau, "{gate:?} on {q}"); + assert_eq!(&*actual.phases, &*expected.phases, "{gate:?} on {q}"); + } + } +} + +#[test] +fn test_y2_h_interference_probabilities_sampling_and_execution() { + use crate::qis::{RuntimeValue, Simulator, sample}; + + for (gate, bit) in [(StandardGate::Y2P, false), (StandardGate::Y2M, true)] { + let mut circuit = Circuit::new(1); + circuit + .append(Instruction::Standard(gate), [Qubit::new(0)], [], None) + .unwrap(); + circuit.h(Qubit::new(0)).unwrap(); + let measured = circuit.measure(Qubit::new(0)).unwrap(); + let state = StabilizerState::from_circuit(&circuit).unwrap(); + let expected = if bit { vec![0.0, 1.0] } else { vec![1.0, 0.0] }; + assert_eq!(state.probabilities().unwrap(), expected, "{gate:?};H"); + let outcome = Outcome::from_bitstring(if bit { "1" } else { "0" }).unwrap(); + for result in [ + state.sample(&measured, 8).unwrap(), + sample(&circuit, 8, Some(42), Simulator::Stabilizer, None).unwrap(), + ] { + assert_eq!(result.counts(), &HashMap::from([(outcome.clone(), 8)])); + } + let execution = StabilizerState::run_circuit(&circuit).unwrap(); + assert_eq!( + execution.classical.value(measured.value()), + Some(&RuntimeValue::Bit(bit)) + ); + } +} + +#[test] +fn test_y2_h_on_bell_state_preserves_expected_signed_correlations() { + for (gate, xx, zz, probabilities) in [ + (StandardGate::Y2P, -1, 1, vec![0.5, 0.0, 0.0, 0.5]), + (StandardGate::Y2M, 1, -1, vec![0.0, 0.5, 0.5, 0.0]), + ] { + let mut circuit = Circuit::new(2); + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + circuit + .append(Instruction::Standard(gate), [Qubit::new(0)], [], None) + .unwrap(); + circuit.h(Qubit::new(0)).unwrap(); + let state = StabilizerState::from_circuit(&circuit).unwrap(); + // Y2P;H applies Z to |Phi+>, yielding |Phi->; Y2M;H applies X, + // yielding |Psi+>. Their Z distributions and XX/ZZ signs differ. + assert_eq!(state.probabilities().unwrap(), probabilities, "{gate:?}"); + for (name, expected) in [("XX", xx), ("ZZ", zz)] { + assert_eq!( + state.pauli_expectation(&name.parse().unwrap()).unwrap(), + expected + ); + } + for shot in state.sample_shots(16) { + assert_eq!(shot.is_one(0) == shot.is_one(1), zz == 1); + } + } +} + +#[test] +fn test_random_clifford_circuits_match_statevector_probabilities_and_observables() { + let mut rng = SmallRng::seed_from_u64(13); + for trial in 0..32 { + let mut circuit = Circuit::new(5); + // Guarantee that both rotations occur on an entangled input in every trial. + circuit.h(Qubit::new(0)).unwrap(); + circuit.cx(Qubit::new(0), Qubit::new(1)).unwrap(); + circuit.y2p(Qubit::new(0)).unwrap(); + circuit.y2m(Qubit::new(1)).unwrap(); + for _ in 0..80 { + let gate = CLIFFORD_GATES[rng.random_range(0..CLIFFORD_GATES.len())]; + let a = rng.random_range(0..5); + let b = (a + rng.random_range(1..5)) % 5; + circuit + .append( + Instruction::Standard(gate), + [Qubit::new(a), Qubit::new(b)] + .into_iter() + .take(gate.num_qubits()), + [], + None, + ) + .unwrap(); + } + let state = StabilizerState::from_circuit(&circuit).unwrap(); + let reference = Statevector::from_circuit(&circuit).unwrap(); + for (basis, (actual, expected)) in state + .probabilities() + .unwrap() + .iter() + .zip(reference.probabilities()) + .enumerate() + { + assert!( + (actual - expected).abs() < 1e-10, + "trial={trial}, basis={basis}" + ); + } + // Generator checks always exercise nonzero expectations; uniformly random + // Paulis alone would mostly have zero expectation on five-qubit states. + let mut observables = state.get_stabilizers(); + for _ in 0..20 { + let mut pauli = PauliString::new(5); + for q in 0..5 { + pauli.set_pauli( + q, + [Pauli::I, Pauli::X, Pauli::Y, Pauli::Z][rng.random_range(0..4)], + ); + } + observables.push(pauli); + } + for pauli in observables { + let actual = state.pauli_expectation(&pauli).unwrap(); + let expected = reference + .expectation(&Hamiltonian::from_pauli(pauli.clone())) + .unwrap(); + assert!( + (actual as f64 - expected).abs() < 1e-10, + "trial={trial}, observable={pauli}" + ); + } + } +} #[test] fn test_new_single_qubit() { @@ -674,7 +896,7 @@ fn test_x2m_four_is_identity() { assert_eq!(&*s.phases, &*original.phases); } -/// Y2P⁴ = Y2M⁴ = identity. +/// Y2P⁴ = Y2M⁴ = -I, equivalent to identity on the stabilizer tableau. #[test] fn test_y2p_four_is_identity() { let original = StabilizerState::new(2); @@ -733,7 +955,7 @@ fn test_x2p_squared_is_x() { assert_eq!(&*after_x2p2.phases, &*after_x.phases); } -/// Y2P² = Y (two √Y gates give Y gate). +/// Y2P² = -iY, equivalent to Y on the stabilizer tableau. #[test] fn test_y2p_squared_is_y() { let mut after_y2p2 = StabilizerState::new(2); @@ -1434,3 +1656,58 @@ fn test_apply_circuit_rejects_classical_control_flow() { let error = StabilizerState::run_circuit(&c).unwrap_err(); assert!(matches!(error, QisError::UnsupportedOperation(_))); } + +#[test] +fn controlled_gphase_returns_unsupported_without_panicking() { + use crate::circuit::{Circuit, StandardGate}; + for theta in [0.0, 0.37, std::f64::consts::FRAC_PI_2] { + let mut circuit = Circuit::from_qubits(vec![Qubit::new(12)]).unwrap(); + circuit + .multi_control( + StandardGate::GPhase, + [Qubit::new(12)], + Vec::::new(), + [theta.into()], + ) + .unwrap(); + let mut state = StabilizerState::new(1); + for result in [ + StabilizerState::from_circuit(&circuit).map(|_| ()), + state.apply_circuit(&circuit), + StabilizerState::run_circuit(&circuit).map(|_| ()), + ] { + assert!( + matches!(result, Err(QisError::UnsupportedOperation(ref message)) + if message.contains("Controlled-GPhase") && message.contains("not supported")), + "unexpected result: {result:?}" + ); + } + } +} + +#[test] +fn controlled_paulis_match_standard_stabilizer_execution() { + use crate::circuit::{Circuit, StandardGate}; + for gate in [StandardGate::X, StandardGate::Y, StandardGate::Z] { + let mut circuit = Circuit::new(2); + circuit.h(Qubit::new(0)).unwrap(); + circuit.h(Qubit::new(1)).unwrap(); + let mut expected = StabilizerState::from_circuit(&circuit).unwrap(); + match gate { + StandardGate::X => expected.apply_cx(0, 1).unwrap(), + StandardGate::Y => expected.apply_cy(0, 1).unwrap(), + StandardGate::Z => expected.apply_cz(0, 1).unwrap(), + _ => unreachable!(), + } + circuit + .multi_control(gate, [Qubit::new(0)], [Qubit::new(1)], []) + .unwrap(); + for actual in [ + StabilizerState::from_circuit(&circuit).unwrap(), + StabilizerState::run_circuit(&circuit).unwrap().state, + ] { + assert_eq!(&*actual.tableau, &*expected.tableau); + assert_eq!(actual.phases, expected.phases); + } + } +} diff --git a/crates/cqlib-core/src/qis/state/state_test.rs b/crates/cqlib-core/src/qis/state/state_test.rs index 86e40296..2c707bb5 100644 --- a/crates/cqlib-core/src/qis/state/state_test.rs +++ b/crates/cqlib-core/src/qis/state/state_test.rs @@ -1,5 +1,4 @@ // This code is part of Cqlib. -// Modified to support reproducible state sampling. // // (C) Copyright China Telecom Quantum Group 2026 // @@ -10,8 +9,6 @@ // Any modifications or derivative works of this code must retain this // copyright notice, and modified files need to carry a notice indicating // that they have been altered from the originals. -// -// Modified to validate terminal measurements and clarify or correct reset behavior. //! Simulation consistency tests between Statevector and DensityMatrix @@ -875,3 +872,64 @@ fn full_measurement_uses_the_supplied_random_stream() { ); } } + +#[test] +fn checked_constructors_reject_dimensions_without_allocating() { + for n in [usize::BITS as usize - 4, usize::BITS as usize, usize::MAX] { + assert!(Statevector::try_new(n).is_err()); + assert!(Statevector::from_state(n, vec![]).is_err()); + } + for n in [ + (usize::BITS as usize - 4).div_ceil(2), + usize::BITS as usize, + usize::MAX, + ] { + assert!(DensityMatrix::try_new(n).is_err()); + assert!(DensityMatrixNoise::try_new(n, None).is_err()); + assert!(DensityMatrix::from_state(n, vec![]).is_err()); + assert!(DensityMatrix::from_density_matrix_state(n, vec![]).is_err()); + assert!(DensityMatrix::try_maximally_mixed(n).is_err()); + } + for n in [0, 1, 3] { + assert_eq!( + Statevector::try_new(n).unwrap().data(), + Statevector::new(n).data() + ); + assert_eq!( + DensityMatrix::try_new(n).unwrap().data(), + DensityMatrix::new(n).data() + ); + assert!( + (DensityMatrixNoise::try_new(n, None) + .unwrap() + .probabilities()[0] + - 1.0) + .abs() + < 1e-12 + ); + } +} + +#[test] +fn nonfinite_pure_states_are_rejected() { + use num_complex::Complex64; + for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX] { + for amp in [Complex64::new(bad, 0.0), Complex64::new(0.0, bad)] { + let state = vec![amp, Complex64::new(0.0, 0.0)]; + assert!(matches!( + Statevector::from_state(1, state.clone()), + Err(QisError::NotNormalized) + )); + assert!(matches!( + DensityMatrix::from_state(1, state), + Err(QisError::NotNormalized) + )); + } + } + for n in [0, 1] { + let mut v = vec![Complex64::new(0.0, 0.0); 1 << n]; + v[0] = Complex64::new(0.0, 1.0); + assert!(Statevector::from_state(n, v.clone()).is_ok()); + assert!(DensityMatrix::from_state(n, v).is_ok()); + } +} diff --git a/crates/cqlib-core/src/qis/state/statevector.rs b/crates/cqlib-core/src/qis/state/statevector.rs index 307972d7..21539d5e 100644 --- a/crates/cqlib-core/src/qis/state/statevector.rs +++ b/crates/cqlib-core/src/qis/state/statevector.rs @@ -351,16 +351,34 @@ impl Statevector { /// assert_eq!(sv.num_qubits, 2); /// assert_eq!(sv.data().len(), 4); // 2^2 amplitudes /// ``` + /// + /// # Panics + /// + /// Panics if the dimension is unrepresentable or allocation fails. + /// Use [`Self::try_new`] to receive an error instead. pub fn new(num_qubits: usize) -> Self { - let size = 1 << num_qubits; + Self::try_new(num_qubits).expect("cannot allocate statevector") + } + + /// Creates the ground state, returning an error for an unrepresentable + /// dimension or a failed allocation. + /// + /// # Errors + /// + /// Returns [`QisError::InvalidParameterValue`] for an unrepresentable + /// dimension, or [`QisError::UnsupportedOperation`] if allocation fails. + pub fn try_new(num_qubits: usize) -> Result { + let size = super::checked_state_len(num_qubits, false)?; // 64-byte aligned allocation — zero-initialised (all amplitudes = 0+0i). - let mut data = AlignedBuffer::::new_zeroed(size); + let mut data = AlignedBuffer::::try_new_zeroed(size).ok_or_else(|| { + QisError::UnsupportedOperation("statevector allocation failed".into()) + })?; data[0] = Complex64::new(1.0, 0.0); // |0...0⟩ - Statevector { + Ok(Statevector { data, num_qubits, qubit_map: None, - } + }) } /// Creates a statevector from initial amplitudes with normalization check. @@ -389,7 +407,7 @@ impl Statevector { /// let sv = Statevector::from_state(2, amps); /// ``` pub fn from_state(num_qubits: usize, initial_state: Vec) -> Result { - let size = 1 << num_qubits; + let size = super::checked_state_len(num_qubits, false)?; if initial_state.len() != size { return Err(QisError::InvalidStateDimension(initial_state.len())); } @@ -397,12 +415,14 @@ impl Statevector { // summing many amplitudes accumulates floating-point roundoff. let norm: f64 = initial_state.iter().map(|c| c.norm_sqr()).sum(); let tolerance = 1e-10 * (size.max(1) as f64); - if (norm - 1.0).abs() >= tolerance { + if !norm.is_finite() || (norm - 1.0).abs() >= tolerance { return Err(QisError::NotNormalized); } // Copy caller-provided Vec into 64-byte aligned buffer. - let mut data = AlignedBuffer::::new_zeroed(size); + let mut data = AlignedBuffer::::try_new_zeroed(size).ok_or_else(|| { + QisError::UnsupportedOperation("statevector allocation failed".into()) + })?; data.as_mut_slice().copy_from_slice(&initial_state); Ok(Statevector { data, @@ -444,13 +464,14 @@ impl Statevector { /// let sv = Statevector::from_circuit(&circuit).unwrap(); /// ``` pub fn from_circuit(circuit: &Circuit) -> Result { - let mut sv = Statevector::new(circuit.num_qubits()); + let mut sv = Statevector::try_new(circuit.num_qubits())?; sv.apply_circuit(circuit)?; Ok(sv) } /// Applies a quantum circuit to this statevector in-place. /// + /// The circuit's resolved global phase is applied, retaining nonzero residuals. /// Once bound to circuit qubit IDs, subsequent circuits must have the same /// IDs in the same order. The mapping is committed only on success; gates /// completed before an error are not rolled back. @@ -500,6 +521,15 @@ impl Statevector { // Decompose circuit to basic gates let circuit = circuit.decompose()?; super::validate_terminal_measurements(&circuit)?; + let global_phase = circuit + .global_phase() + .evaluate(&None) + .map_err(|_| QisError::CircuitError(CircuitError::SymbolicParameterError))?; + if !global_phase.is_finite() { + return Err(QisError::InvalidParameterValue( + "circuit global phase must be finite".into(), + )); + } let sv = self; let qubit_map = super::prepare_qubit_map(&circuit.qubits(), &sv.qubit_map)?; @@ -546,44 +576,31 @@ impl Statevector { let num_controls = mc_gate.num_ctrl_qubits(); let base_gate = mc_gate.base_gate(); - if num_controls == 1 { - // Single-controlled gate - let control = qubit_indices[0]; - let target = qubit_indices[1]; - match base_gate { - StandardGate::X => sv.apply_cx(control, target)?, - StandardGate::Y => sv.apply_cy(control, target)?, - StandardGate::Z => sv.apply_cz(control, target)?, - StandardGate::RX => { - let theta = params[0]; - sv.apply_crx(control, target, theta)?; - } - StandardGate::RY => { - let theta = params[0]; - sv.apply_cry(control, target, theta)?; - } - StandardGate::RZ => { - let theta = params[0]; - sv.apply_crz(control, target, theta)?; - } - _ => { - let matrix = mc_gate.matrix(¶ms).map_err(|_| { - QisError::CircuitError(CircuitError::NoMatrixRepresentation) - })?; - sv.apply_unitary_gate(&qubit_indices, &matrix)?; - } + match (num_controls, *base_gate) { + (0, StandardGate::GPhase) => { + sv.apply_standard_gate(*base_gate, &qubit_indices, ¶ms)? + } + (1, StandardGate::X) => sv.apply_cx(qubit_indices[0], qubit_indices[1])?, + (1, StandardGate::Y) => sv.apply_cy(qubit_indices[0], qubit_indices[1])?, + (1, StandardGate::Z) => sv.apply_cz(qubit_indices[0], qubit_indices[1])?, + (1, StandardGate::RX) => { + sv.apply_crx(qubit_indices[0], qubit_indices[1], params[0])? + } + (1, StandardGate::RY) => { + sv.apply_cry(qubit_indices[0], qubit_indices[1], params[0])? + } + (1, StandardGate::RZ) => { + sv.apply_crz(qubit_indices[0], qubit_indices[1], params[0])? + } + (2, StandardGate::X) => { + sv.apply_ccx(qubit_indices[0], qubit_indices[1], qubit_indices[2])? + } + _ => { + let matrix = mc_gate.matrix(¶ms).map_err(|_| { + QisError::CircuitError(CircuitError::NoMatrixRepresentation) + })?; + sv.apply_unitary_gate(&qubit_indices, &matrix)?; } - } else if num_controls == 2 && *base_gate == StandardGate::X { - // Toffoli gate - let c0 = qubit_indices[0]; - let c1 = qubit_indices[1]; - let target = qubit_indices[2]; - sv.apply_ccx(c0, c1, target)?; - } else { - let matrix = mc_gate.matrix(¶ms).map_err(|_| { - QisError::CircuitError(CircuitError::NoMatrixRepresentation) - })?; - sv.apply_unitary_gate(&qubit_indices, &matrix)?; } } Instruction::UnitaryGate(u_gate) => { @@ -624,6 +641,7 @@ impl Statevector { } } + sv.apply_gphase(global_phase)?; sv.qubit_map = Some(qubit_map); Ok(()) } @@ -2668,7 +2686,7 @@ impl Statevector { /// # Arguments /// * `phi` - Phase angle pub fn apply_gphase(&mut self, phi: f64) -> Result<(), QisError> { - if phi.abs() < 1e-15 { + if phi == 0.0 { return Ok(()); } let phase = Complex64::from_polar(1.0, phi); diff --git a/crates/cqlib-core/src/qis/state/statevector_test.rs b/crates/cqlib-core/src/qis/state/statevector_test.rs index de277f7b..83fc75d1 100644 --- a/crates/cqlib-core/src/qis/state/statevector_test.rs +++ b/crates/cqlib-core/src/qis/state/statevector_test.rs @@ -908,6 +908,35 @@ fn test_global_phase() { ); } +#[test] +fn circuit_evolution_applies_global_phase_including_small_residuals() { + use crate::circuit::Parameter; + for num_qubits in [0, 1] { + for angle in [0.3, 1e-12, 1e-20] { + let mut circuit = Circuit::new(num_qubits); + circuit.set_global_phase(Parameter::from(angle)); + let state = Statevector::from_circuit(&circuit).unwrap(); + let expected = Complex64::from_polar(1.0, angle); + assert_eq!(state.data[0], expected); + let mut incremental = Statevector::new(num_qubits); + incremental.apply_circuit(&circuit).unwrap(); + assert_eq!(incremental.data[0], expected); + } + } +} + +#[test] +fn circuit_evolution_rejects_unbound_global_phase_before_mutating() { + use crate::circuit::Parameter; + let mut circuit = Circuit::new(1); + circuit.x(Qubit::new(0)).unwrap(); + circuit.set_global_phase(Parameter::symbol("phi")); + let mut state = Statevector::new(1); + let before = state.data.clone(); + assert!(state.apply_circuit(&circuit).is_err()); + assert_eq!(&state.data[..], &before[..]); +} + #[test] fn test_relative_phase() { // S gate introduces relative phase @@ -2252,3 +2281,117 @@ fn test_apply_pauli_rotation_rejects_imaginary_global_phase() { pauli.phase = Phase::I; assert!(state.apply_pauli_rotation(&pauli, 0.2).is_err()); } + +#[test] +fn controlled_gphase_circuit_evolution() { + for ids in [[0, 1, 2], [12, 5, 31]] { + let qubits = ids.map(Qubit::new); + for controls in [ + vec![qubits[2]], + vec![qubits[2], qubits[0]], + vec![qubits[0], qubits[2]], + ] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut preparation = Circuit::from_qubits(qubits.to_vec()).unwrap(); + for qubit in qubits { + preparation.h(qubit).unwrap(); + } + preparation.s(qubits[1]).unwrap(); + let mut phase = Circuit::from_qubits(qubits.to_vec()).unwrap(); + phase + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [theta.into()], + ) + .unwrap(); + let mut circuit = preparation.clone(); + circuit + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [theta.into()], + ) + .unwrap(); + let mask = controls.iter().fold(0usize, |mask, q| { + mask | (1 << qubits.iter().position(|candidate| candidate == q).unwrap()) + }); + let expected: Vec = (0..8) + .map(|index| { + let amplitude = if index & 2 == 0 { + Complex64::new(1.0, 0.0) + } else { + Complex64::new(0.0, 1.0) + } / 8.0_f64.sqrt(); + if index & mask == mask { + amplitude * Complex64::from_polar(1.0, theta) + } else { + amplitude + } + }) + .collect(); + let expected_data = expected.clone(); + let actual = Statevector::from_circuit(&circuit).unwrap(); + let mut incremental = Statevector::new(3); + incremental.apply_circuit(&preparation).unwrap(); + incremental.apply_circuit(&phase).unwrap(); + for values in [actual.data(), incremental.data()] { + for (actual, expected) in values.iter().zip(&expected_data) { + assert!( + (actual - expected).norm() < 1e-12, + "{actual:?} != {expected:?}" + ); + } + } + let mut inverse = Circuit::from_qubits(qubits.to_vec()).unwrap(); + inverse + .multi_control( + StandardGate::GPhase, + controls.clone(), + Vec::::new(), + [(-theta).into()], + ) + .unwrap(); + incremental.apply_circuit(&inverse).unwrap(); + let baseline = Statevector::from_circuit(&preparation).unwrap(); + for (actual, expected) in incremental.data().iter().zip(baseline.data()) { + assert!((actual - expected).norm() < 1e-12); + } + } + } + } +} + +#[test] +fn zero_control_gphase_circuit_evolution() { + use crate::circuit::gate::{Instruction, MCGate}; + for num_qubits in [0, 1, 3] { + for theta in [0.0, 0.37, -0.51, PI] { + let mut circuit = Circuit::new(num_qubits); + if num_qubits > 0 { + circuit.h(Qubit::new(0)).unwrap(); + } + circuit + .append( + Instruction::McGate(Box::new(MCGate::new(0, StandardGate::GPhase))), + Vec::::new(), + [theta.into()], + None, + ) + .unwrap(); + let actual = Statevector::from_circuit(&circuit).unwrap(); + let mut amplitudes = vec![Complex64::new(0.0, 0.0); 1 << num_qubits]; + amplitudes[0] = Complex64::from_polar(1.0, theta); + if num_qubits > 0 { + amplitudes[0] /= 2.0_f64.sqrt(); + amplitudes[1] = amplitudes[0]; + } + let expected = amplitudes; + for (actual, expected) in actual.data().iter().zip(&expected) { + assert!((actual - expected).norm() < 1e-12); + } + } + } +} diff --git a/crates/cqlib-core/src/visualization/state/math.rs b/crates/cqlib-core/src/visualization/state/math.rs index 490fb7a8..c65890da 100644 --- a/crates/cqlib-core/src/visualization/state/math.rs +++ b/crates/cqlib-core/src/visualization/state/math.rs @@ -84,6 +84,8 @@ pub fn local_bloch_vectors( /// The returned labels enumerate tensor products over `I`, `X`, `Y`, and `Z`. /// Values are expectation coefficients `Tr(rho P)` in the same qubit indexing convention /// used by the statevector basis: qubit `q` corresponds to bit `1 << q`. +/// Labels follow [`crate::qis::pauli::PauliString`]: the highest-index qubit is on +/// the left by default. `reverse_bits` reverses the displayed characters only. pub(crate) fn pauli_coefficients( num_qubits: usize, rho: &[Complex64], @@ -97,6 +99,11 @@ pub(crate) fn pauli_coefficients( ))); } + let display_qubits: Vec = if reverse_bits { + (0..num_qubits).collect() + } else { + (0..num_qubits).rev().collect() + }; let mut out = Vec::with_capacity(total); for idx in 0..total { let mut code = idx; @@ -111,11 +118,6 @@ pub(crate) fn pauli_coefficients( ops.push((qubit, op)); code /= 4; } - let display_qubits: Vec = if reverse_bits { - (0..num_qubits).rev().collect() - } else { - (0..num_qubits).collect() - }; let label = display_qubits .iter() .map(|qubit| match ops[*qubit].1 { diff --git a/crates/cqlib-core/src/visualization/state/math_test.rs b/crates/cqlib-core/src/visualization/state/math_test.rs index 318a584b..1b14e9ad 100644 --- a/crates/cqlib-core/src/visualization/state/math_test.rs +++ b/crates/cqlib-core/src/visualization/state/math_test.rs @@ -14,7 +14,8 @@ use super::math::pauli_coefficients; use super::*; -use crate::qis::Statevector; +use crate::qis::pauli::PauliString; +use crate::qis::{DensityMatrix, Statevector}; use num_complex::Complex64; fn plus_state() -> Statevector { @@ -86,3 +87,81 @@ fn paulivec_contains_expected_plus_y() { .any(|(label, value)| label == "Y" && (*value - 1.0).abs() < 1e-10) ); } + +#[test] +fn paulivec_labels_identify_the_correct_qubit() { + // q0 = |+>, q1 = |0>: IX measures q0, XI measures q1. + let state = Statevector::from_state( + 2, + vec![ + Complex64::new(1.0 / 2.0_f64.sqrt(), 0.0), + Complex64::new(1.0 / 2.0_f64.sqrt(), 0.0), + Complex64::new(0.0, 0.0), + Complex64::new(0.0, 0.0), + ], + ) + .unwrap(); + let (_, rho) = state_to_density_matrix(&state).unwrap(); + for reverse_bits in [false, true] { + let coeffs = pauli_coefficients(2, &rho, reverse_bits).unwrap(); + for (label, expected) in [("IX", 1.0), ("XI", 0.0), ("IZ", 0.0), ("ZI", 1.0)] { + let displayed = if reverse_bits { + label.chars().rev().collect::() + } else { + label.to_string() + }; + let value = coeffs.iter().find(|(s, _)| *s == displayed).unwrap().1; + assert!((value - expected).abs() < 1e-10, "{displayed}: {value}"); + } + } +} + +fn assert_paulivec_matches_observables( + state: &impl StateVisualizationSource, + expectation: impl Fn(&PauliString) -> f64, +) { + let (num_qubits, rho) = state_to_density_matrix(state).unwrap(); + for reverse_bits in [false, true] { + let coeffs = pauli_coefficients(num_qubits, &rho, reverse_bits).unwrap(); + assert_eq!(coeffs.len(), 4usize.pow(num_qubits as u32)); + for (label, value) in coeffs { + let semantic_label = if reverse_bits { + label.chars().rev().collect::() + } else { + label.clone() + }; + let pauli: PauliString = semantic_label.parse().unwrap(); + let expected = expectation(&pauli); + assert!( + (value - expected).abs() < 1e-10, + "{num_qubits} qubits, reverse_bits={reverse_bits}, {label}: {value} != {expected}" + ); + } + } +} + +#[test] +fn paulivec_coefficients_match_observables_for_pure_and_mixed_states() { + for num_qubits in 1..=3 { + let dim = 1 << num_qubits; + // Asymmetric complex amplitudes exercise X, Y, Z and negative coefficients. + let mut amplitudes: Vec<_> = (0..dim) + .map(|i| Complex64::new(((i + 1) as f64 * 0.71).sin(), ((i + 2) as f64 * 0.43).cos())) + .collect(); + let norm = amplitudes.iter().map(|a| a.norm_sqr()).sum::().sqrt(); + for amplitude in &mut amplitudes { + *amplitude /= norm; + } + let pure = Statevector::from_state(num_qubits, amplitudes).unwrap(); + assert_paulivec_matches_observables(&pure, |p| pure.expectation(p).unwrap()); + + // A convex mixture with |11...1><11...1| is a genuine mixed state. + let (_, mut rho) = state_to_density_matrix(&pure).unwrap(); + for value in &mut rho { + *value *= 0.7; + } + rho[dim * dim - 1] += Complex64::new(0.3, 0.0); + let mixed = DensityMatrix::from_density_matrix_state(num_qubits, rho).unwrap(); + assert_paulivec_matches_observables(&mixed, |p| mixed.expectation(p).unwrap()); + } +} diff --git a/crates/cqlib-core/src/visualization/state/plot.rs b/crates/cqlib-core/src/visualization/state/plot.rs index 2243f3ed..cadd93d4 100644 --- a/crates/cqlib-core/src/visualization/state/plot.rs +++ b/crates/cqlib-core/src/visualization/state/plot.rs @@ -195,6 +195,11 @@ pub fn plot_state_city( /// Plot Pauli-basis expectation values as an SVG bar chart. /// +/// By default, labels follow [`crate::qis::pauli::PauliString`]: the rightmost +/// character acts on qubit 0. For example, `IX` measures X on qubit 0 of a +/// two-qubit state. Setting `options.reverse_bits` reverses the characters in +/// each label without changing the state or the corresponding expectation value. +/// /// # Arguments /// /// * `state` - Input core state object accepted by state visualization routines. diff --git a/crates/cqlib-core/src/visualization/state/plot_test.rs b/crates/cqlib-core/src/visualization/state/plot_test.rs index 256ebb04..25e286a6 100644 --- a/crates/cqlib-core/src/visualization/state/plot_test.rs +++ b/crates/cqlib-core/src/visualization/state/plot_test.rs @@ -172,6 +172,54 @@ fn paulivec_matches_reference_image() { assert_state_visual_match(&svg, "paulivec_plus.png"); } +#[test] +fn paulivec_svg_labels_match_asymmetric_state() { + let state = Statevector::from_state( + 2, + vec![ + Complex64::new(1.0 / 2.0_f64.sqrt(), 0.0), + Complex64::new(1.0 / 2.0_f64.sqrt(), 0.0), + Complex64::new(0.0, 0.0), + Complex64::new(0.0, 0.0), + ], + ) + .unwrap(); + let density = DensityMatrix::from_state(2, state.data().to_vec()).unwrap(); + for reverse_bits in [false, true] { + let options = StatePlotOptions { + reverse_bits, + ..StatePlotOptions::default() + }; + for svg in [ + plot_state_paulivec(&state, &options).unwrap(), + plot_state_paulivec(&density, &options).unwrap(), + ] { + let bar = |label: &str| { + let label_start = svg.find(&format!(">{label}")).unwrap(); + let bar_start = svg[..label_start].rfind(" 1.0); + for (label, expected) in [("IX", 1.0), ("XI", 0.0), ("IZ", 0.0), ("ZI", 1.0)] { + let displayed = if reverse_bits { + label.chars().rev().collect::() + } else { + label.to_string() + }; + let (y, height) = bar(&displayed); + if expected == 1.0 { + assert_eq!((y, height), (one_y, one_height), "{displayed}"); + } else { + assert_eq!(height, 1.0, "{displayed}"); + assert!((y - one_y - one_height).abs() < 1e-3, "{displayed}"); + } + } + } + } +} + #[test] fn density_matrix_uses_same_state_plot_api() { let statevector = plus_state(); diff --git a/crates/cqlib/Cargo.toml b/crates/cqlib/Cargo.toml index d1c96364..9e43e789 100644 --- a/crates/cqlib/Cargo.toml +++ b/crates/cqlib/Cargo.toml @@ -21,10 +21,9 @@ categories = [ "science", "simulation", "algorithms", - "science::physics", "data-structures" ] [dependencies] -cqlib-core = { path = "../cqlib-core", version = "0.1.0-beta.1" } +cqlib-core = { path = "../cqlib-core", version = "0.1.0-beta.7" } diff --git a/docs/api/cn/c/1_ir/3_qasm3.md b/docs/api/cn/c/1_ir/3_qasm3.md index 58715594..5ba196e4 100644 --- a/docs/api/cn/c/1_ir/3_qasm3.md +++ b/docs/api/cn/c/1_ir/3_qasm3.md @@ -84,6 +84,7 @@ C 绑定提供 OpenQASM 3.0 文本与 `CCircuit` 之间的四个转换入口。 - 子程序与外部调用:`def` 子程序、`extern` - 硬件相关:硬件量子比特、`output` 声明,以及除角度与浮点以外的 `input` 声明 - 其它语句:`alias`、`pragma`、注解、旧式声明 +- 程序终止:`end`;任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 - 门修饰符:`negctrl`、`pow`;`ctrl` 与 `inv` 仅在目标门存在对应实现时可用 - 部分标准门:`ch`、`cp`、`cu`、`cswap` - 控制流:运行时条件的 `while` 会被语义检查拒绝;`for` 只支持范围为常量的静态展开形式 diff --git a/docs/api/cn/c/3_qis/0_overview.md b/docs/api/cn/c/3_qis/0_overview.md index 18e0c9fe..3807ce50 100644 --- a/docs/api/cn/c/3_qis/0_overview.md +++ b/docs/api/cn/c/3_qis/0_overview.md @@ -84,3 +84,5 @@ int main(void) { ``` 噪声模型句柄 `CNoiseModel` 的构造与噪声登记见 [NoiseModel](../2_device/4_noise.md)。 + +新增的[费米子代数与 Jordan–Wigner](10_fermion.md)和 [checked Hamiltonian 代数](7_hamiltonian.md#带校验的稀疏-pauli-代数)使用“错误码 + 输出指针”接口;构造结果通过输出指针返回,判断通过字节输出写入 0/1。旧 QIS 接口保持原有约定。 diff --git a/docs/api/cn/c/3_qis/10_fermion.md b/docs/api/cn/c/3_qis/10_fermion.md new file mode 100644 index 00000000..888a3d8d --- /dev/null +++ b/docs/api/cn/c/3_qis/10_fermion.md @@ -0,0 +1,179 @@ +# 费米子代数与 Jordan–Wigner(C) + +`CFermionicOp` 是有序升降算符乘积的稀疏复数线性组合。模式从零编号;乘积 `A B` 表示 B 先作用。相同有序乘积自动合并,仅删除精确零;不会隐式正规序或截断小系数。零算符和恒等算符都保留声明的模式数,支持零模式。 + +## ABI 与数据 + +所有返回 `int32_t` 的新接口以 `0` 表示成功。对象通过 `**out` 返回,标量通过输出指针返回;失败不改变输出或原对象。对象结果独立拥有,使用 `fermionic_op_free` 释放;输入借用并复制。调用方传入空输出槽,并提供有效、对齐、存活的指针;输出存储不得相互重叠或与句柄内部存储重叠。同一句柄被修改时,不可并发读取。数组长度为零允许 NULL;非空数组必须指向足够存储。 + +错误码:`-1` 必需指针为空,`-2` 模式或项索引越界,`-8` 非法标签、模式数不匹配、非有限系数或算术溢出、非法容差、容量不足或无法表示的数组长度,`-7` 不支持的 Pauli 表示规模。判断通过 `uint8_t *out` 写入 0/1,成功返回值始终为 0。 + +```c +typedef struct CFermionicOp CFermionicOp; +#define FERMIONIC_CREATE 0 +#define FERMIONIC_ANNIHILATE 1 +typedef struct CFermionicLadder { + size_t mode; + uint8_t kind; +} CFermionicLadder; +typedef struct CFermionicTerm { + const CFermionicLadder *ladders; + size_t len; + Complex64 coefficient; +} CFermionicTerm; +``` + +## 构造 + +```c +int32_t fermionic_op_new(size_t num_modes, CFermionicOp **out); + +int32_t fermionic_op_identity(size_t num_modes, CFermionicOp **out); + +int32_t fermionic_op_from_term(size_t num_modes, + const CFermionicLadder *term, + size_t len, + Complex64 coefficient, + CFermionicOp **out); + +int32_t fermionic_op_from_terms(size_t num_modes, + const CFermionicTerm *terms, + size_t len, + CFermionicOp **out); + +int32_t fermionic_op_creation(size_t num_modes, size_t mode, CFermionicOp **out); + +int32_t fermionic_op_annihilation(size_t num_modes, size_t mode, CFermionicOp **out); + +int32_t fermionic_op_number(size_t num_modes, size_t mode, CFermionicOp **out); + +int32_t fermionic_op_total_number(size_t num_modes, CFermionicOp **out); + +int32_t fermionic_op_excitation_generator(size_t num_modes, + const size_t *sources, + size_t sources_len, + const size_t *targets, + size_t targets_len, + CFermionicOp **out); +``` + +- `new` 创建零,`identity` 创建一;`from_term` 的空乘积为 identity,`from_terms` 的空求和为 zero。批量输入及嵌套升降算符数组只在调用期间借用。即使系数为零,也校验标签和模式。 +- `creation/annihilation/number` 分别构造 a†、a、a†a;`total_number` 为所有模式 number 之和。 +- 激发生成元 `G=i(T−T†)`,其中 T 的 target 创建算符按输入顺序排列,source 湮灭算符按逆序排列。两侧必须非空、等长、各自无重复且互不重叠。奇排列改变符号,无排序、阶乘或自旋轨道约定。 + +## 生命周期与读取 + +```c +void fermionic_op_free(CFermionicOp *ptr); + +int32_t fermionic_op_copy(const CFermionicOp *ptr, CFermionicOp **out); + +int32_t fermionic_op_num_modes(const CFermionicOp *ptr, size_t *out); + +int32_t fermionic_op_num_terms(const CFermionicOp *ptr, size_t *out); + +int32_t fermionic_op_is_zero(const CFermionicOp *ptr, uint8_t *out); + +int32_t fermionic_op_equals(const CFermionicOp *left, + const CFermionicOp *right, + uint8_t *out); + +int32_t fermionic_op_term_len(const CFermionicOp *ptr, size_t index, size_t *out); + +int32_t fermionic_op_get_term(const CFermionicOp *ptr, + size_t index, + CFermionicLadder *buffer, + size_t capacity, + Complex64 *out_coefficient); +``` + +`free(NULL)` 合法;`copy` 返回独立副本。`is_zero` 检查存储是否为空,`equals` 比较存储结构和模式数(模式数不同返回 false)。代数比较使用 `equiv`。 + +先调用 `term_len` 获取项长度,再分配 buffer 并调用 `get_term`;capacity 可以大于所需长度,额外元素保持原值。空乘积允许 NULL buffer。按 core 的确定性结构顺序读取;修改算符后应重新查询长度和索引。输出数组是副本,没有需要释放的内部指针。 + +## 代数 + +```c +int32_t fermionic_op_add_term(CFermionicOp *ptr, + const CFermionicLadder *term, + size_t len, + Complex64 coefficient); + +int32_t fermionic_op_add(const CFermionicOp *left, + const CFermionicOp *right, + CFermionicOp **out); + +int32_t fermionic_op_sub(const CFermionicOp *left, + const CFermionicOp *right, + CFermionicOp **out); + +int32_t fermionic_op_mul(const CFermionicOp *left, + const CFermionicOp *right, + CFermionicOp **out); + +int32_t fermionic_op_scaled(const CFermionicOp *ptr, + Complex64 factor, + CFermionicOp **out); + +int32_t fermionic_op_adjoint(const CFermionicOp *ptr, CFermionicOp **out); + +int32_t fermionic_op_normal_order(const CFermionicOp *ptr, CFermionicOp **out); + +int32_t fermionic_op_chop(CFermionicOp *ptr, double atol); + +int32_t fermionic_op_equiv(const CFermionicOp *left, + const CFermionicOp *right, + double atol, + uint8_t *out); + +int32_t fermionic_op_is_hermitian(const CFermionicOp *ptr, double atol, uint8_t *out); +``` + +`add_term/chop` 原地修改,其余对象运算返回副本。`mul` 不自动正规序;`adjoint` 共轭系数、逆转乘积并交换升降种类。`normal_order` 将创建算符放在湮灭算符前,每组按模式升序,包含反对易收缩项。 + +`chop` 删除模长 ≤ atol 的系数。`equiv` 对差正规序后比较系数,要求模式数相同;`is_hermitian` 与伴随比较。atol 必须有限且非负,精确比较显式传入 0。它是系数容差,不是矩阵算符范数误差界。 + +## Jordan–Wigner + +```c +int32_t jordan_wigner_map_operator(const CFermionicOp *ptr, CHamiltonian **out); + +int32_t jordan_wigner_num_qubits(size_t num_modes, size_t *out); + +int32_t jordan_wigner_map_occupation(const uint8_t *occupation, + size_t len, + uint8_t *out_bits, + size_t capacity); +``` + +无状态映射无需句柄。mode p 对应 qubit p,Z 链覆盖所有更低模式:creation = Z链(X−iY)/2,annihilation = Z链(X+iY)/2。qubit 0 为最低有效位,也是显示的 Pauli 字符串最右字符。 + +`map_operator` 返回独立 `CHamiltonian`,使用 `hamiltonian_free` 释放;非厄米输入合法,厄米性要求由期望值和演化等下游接口检查。映射不构造稠密矩阵,但 k 个升降算符的乘积在合并前可能展开为 2^k 项。 + +`map_occupation` 仅接受 0/1,占据长度决定模式数;输出字节 bits[p] 对应 qubit p。capacity 至少为 len,输入输出允许重叠;空输入为零模式真空。 + +## 示例 + +```c +#include "cqlib_c.h" + +int main(void) { + const size_t sources[] = {0}, targets[] = {1}; + CFermionicOp *g = NULL; + CHamiltonian *h = NULL; + if (fermionic_op_excitation_generator(2, sources, 1, targets, 1, &g) != 0) { + return 1; + } + if (jordan_wigner_map_operator(g, &h) != 0) { + fermionic_op_free(g); + return 1; + } + CCircuit *u = hamiltonian_to_evolution_circuit( + h, 0.37, 1, TROTTER_MODE_SECOND_ORDER); + const int result = u == NULL ? 1 : 0; + circuit_free(u); + hamiltonian_free(h); + fermionic_op_free(g); + return result; +} +``` diff --git a/docs/api/cn/c/3_qis/1_statevector.md b/docs/api/cn/c/3_qis/1_statevector.md index fface258..dbca7a73 100644 --- a/docs/api/cn/c/3_qis/1_statevector.md +++ b/docs/api/cn/c/3_qis/1_statevector.md @@ -8,6 +8,8 @@ ### statevector_new(num_qubits) +状态维度无法表示或状态内存分配失败时返回 `NULL`。支持零比特状态。 + ```c struct CStatevector *statevector_new(uintptr_t num_qubits); ``` diff --git a/docs/api/cn/c/3_qis/2_density_matrix.md b/docs/api/cn/c/3_qis/2_density_matrix.md index b0037fcf..c57a12e5 100644 --- a/docs/api/cn/c/3_qis/2_density_matrix.md +++ b/docs/api/cn/c/3_qis/2_density_matrix.md @@ -8,6 +8,8 @@ ### density_matrix_new(num_qubits) +状态维度无法表示或状态内存分配失败时返回 `NULL`。支持零比特状态。 + ```c struct CDensityMatrix *density_matrix_new(uintptr_t num_qubits); ``` @@ -20,6 +22,8 @@ struct CDensityMatrix *density_matrix_new(uintptr_t num_qubits); ### density_matrix_maximally_mixed(num_qubits) +状态维度无法表示或状态内存分配失败时返回 `NULL`。支持零比特状态。 + ```c struct CDensityMatrix *density_matrix_maximally_mixed(uintptr_t num_qubits); ``` @@ -32,6 +36,8 @@ struct CDensityMatrix *density_matrix_maximally_mixed(uintptr_t num_qubits); ### density_matrix_zeros(num_qubits) +状态维度无法表示或状态内存分配失败时返回 `NULL`。支持零比特状态。 + ```c struct CDensityMatrix *density_matrix_zeros(uintptr_t num_qubits); ``` diff --git a/docs/api/cn/c/3_qis/3_density_matrix_noise.md b/docs/api/cn/c/3_qis/3_density_matrix_noise.md index 03ddac33..1f5ade40 100644 --- a/docs/api/cn/c/3_qis/3_density_matrix_noise.md +++ b/docs/api/cn/c/3_qis/3_density_matrix_noise.md @@ -8,6 +8,8 @@ ### density_matrix_noise_new(num_qubits, noise_model) +状态维度无法表示或状态内存分配失败时返回 `NULL`。支持零比特状态。 + ```c struct CDensityMatrixNoise *density_matrix_noise_new(uintptr_t num_qubits, const struct CNoiseModel *noise_model); @@ -248,7 +250,7 @@ int32_t density_matrix_noise_probabilities_with_readout(const struct CDensityMat - `ptr` (`const CDensityMatrixNoise*`):噪声模拟器句柄。 - `buffer` (`double*`):输出缓冲。 - `len` (`uintptr_t`):缓冲长度,必须等于 `density_matrix_noise_probabilities_with_readout_len`。 -- `qubits` (`const uint32_t*`):施加读出误差的比特数组;`qubit_len` 为 0 时可为 NULL,此时结果与 `density_matrix_noise_probabilities` 一致。 +- `qubits` (`const uint32_t*`):施加读出误差的存储位置数组;绑定线路后按位置对应的线路比特 ID 查询噪声模型,未绑定时 ID 与位置相同。输出始终为按存储位序排列的完整概率数组。`qubit_len` 为 0 时可为 NULL,此时结果与 `density_matrix_noise_probabilities` 一致。 - `qubit_len` (`uintptr_t`):比特数量。 返回:`0` 成功;`-1` NULL 指针;`-2` 比特越界;`-8` `len` 与实际数量不符。 diff --git a/docs/api/cn/c/3_qis/6_pauli.md b/docs/api/cn/c/3_qis/6_pauli.md index 5079672e..ceae851b 100644 --- a/docs/api/cn/c/3_qis/6_pauli.md +++ b/docs/api/cn/c/3_qis/6_pauli.md @@ -132,13 +132,15 @@ int32_t pauli_mul_with_phase(uint8_t left, uint8_t right, uint8_t *out_pauli, Co ### pauli_string_matrix_len(ptr) -返回稠密矩阵的边长 `2^N`;NULL 返回 0。 +返回稠密矩阵的边长 `2^N`;NULL 或边长无法表示时返回 0。 ### pauli_string_matrix(ptr, buffer, len) 把 `2^N × 2^N` 稠密矩阵按行主序拷入 `buffer`(`Complex64` 值)。`len` 必须等于 `pauli_string_matrix_len(ptr) * pauli_string_matrix_len(ptr)`。 -返回:0 成功;-1 空指针;-8 `len` 与矩阵元素数不符。 +返回:0 成功;-1 空指针;-7 元素数或字节数无法表示,或分配失败;-8 `len` 与矩阵元素数不符。失败不改写缓冲区。 + +可表示的边长不保证完整矩阵可以分配;调用方应在计算 `dim * dim` 前检查溢出。 --- @@ -169,6 +171,7 @@ int32_t pauli_mul_with_phase(uint8_t left, uint8_t right, uint8_t *out_pauli, Co ## 示例 ```c +#include #include #include #include "cqlib_c.h" @@ -192,6 +195,11 @@ int main(void) { struct CPauliString *zz = pauli_string_parse("ZZI"); int32_t commutes = pauli_string_commutes_with(ps, zz); /* 0(比特 2 上 X 与 Z 反对易) */ + printf("%s: qubits=%" PRIuPTR ", p2=%u, p0=%u\n", text, n, + (unsigned)p2, (unsigned)p0); + printf("x_mask=%" PRIuPTR ", z_mask=%" PRIuPTR ", commutes=%" PRId32 "\n", + x_mask, z_mask, commutes); + /* 4. 两步式读取 8x8 稠密矩阵 */ uintptr_t dim = pauli_string_matrix_len(ps); /* 8 */ Complex64 *matrix = malloc(dim * dim * sizeof(Complex64)); diff --git a/docs/api/cn/c/3_qis/7_hamiltonian.md b/docs/api/cn/c/3_qis/7_hamiltonian.md index ad066c5f..27e9e7fd 100644 --- a/docs/api/cn/c/3_qis/7_hamiltonian.md +++ b/docs/api/cn/c/3_qis/7_hamiltonian.md @@ -99,9 +99,11 @@ Trotter-Suzuki 分解模式标签(`hamiltonian_to_trotter_circuit` 与 `hamilt ### hamiltonian_to_matrix_len(ptr) / hamiltonian_to_matrix(ptr, buffer, len) -两步式读取稠密矩阵:`*_len` 返回边长 `2^N`(NULL 返回 0),填充接口把 `2^N × 2^N` 矩阵按行主序拷入 `buffer`(`Complex64` 值)。`len` 必须等于边长的平方。 +两步式读取稠密矩阵:`*_len` 返回边长 `2^N`(NULL 或边长无法表示时返回 0),填充接口把 `2^N × 2^N` 矩阵按行主序拷入 `buffer`(`Complex64` 值)。`len` 必须等于边长的平方。 -返回(填充接口):0 成功;-1 空指针;-8 `len` 与矩阵元素数不符。 +返回(填充接口):0 成功;-1 空指针;-7 元素数或字节数无法表示,或分配失败;-8 `len` 与矩阵元素数不符。失败不改写缓冲区。 + +可表示的边长不保证完整矩阵可以分配;调用方应在计算 `dim * dim` 前检查溢出。 --- @@ -212,6 +214,7 @@ int32_t hamiltonian_variance_statevector(const struct CHamiltonian *ptr, ## 示例 ```c +#include #include #include #include "cqlib_c.h" @@ -230,6 +233,8 @@ int main(void) { uintptr_t nq = hamiltonian_num_qubits(ham); /* 2 */ uintptr_t nt = hamiltonian_num_terms(ham); /* 2 */ int32_t commute = hamiltonian_all_terms_commute(ham); /* 1(两单项对易) */ + printf("qubits=%" PRIuPTR ", terms=%" PRIuPTR ", commute=%" PRId32 "\n", + nq, nt, commute); hamiltonian_simplify(ham); /* 3. 两步式读取 4x4 稠密矩阵 */ @@ -280,3 +285,86 @@ int main(void) { ``` 哈密顿量作为可观测量用于误差缓解流程(见 [零噪声外推](../6_error_mitigation/1_zne.md)、[虚拟蒸馏](../6_error_mitigation/2_virtual_distillation.md)),其期望值可直接由态矢量模拟器计算(见 [态矢量](1_statevector.md))。 + + +## 带校验的稀疏 Pauli 代数 + +`CHamiltonian` 同时表示一般非厄米稀疏算符。以下新接口采用与[费米子绑定](10_fermion.md)相同的错误码和输出约定:成功为 0,通过 `**out` 返回独立句柄,失败不改写输出或输入。输入 Pauli 句柄借用并复制,不消耗。保留旧 `from_pauli` 的所有权转移、原地 `scale` 和近零截断 `simplify` 行为。 + +```c +typedef struct CHamiltonianTerm { + const CPauliString *pauli; + Complex64 coefficient; +} CHamiltonianTerm; + +int32_t hamiltonian_identity(size_t num_qubits, CHamiltonian **out); + +int32_t hamiltonian_from_terms(size_t num_qubits, + const CHamiltonianTerm *terms, + size_t len, + CHamiltonian **out); + +int32_t hamiltonian_copy(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_normalized(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_normalized_hermitian(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_add(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_sub(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_mul(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_scaled(const CHamiltonian *ptr, + Complex64 factor, + CHamiltonian **out); + +int32_t hamiltonian_adjoint(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_tensor(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_remap_qubits(const CHamiltonian *ptr, + const size_t *mapping, + size_t len, + size_t target_width, + CHamiltonian **out); + +int32_t hamiltonian_chop(CHamiltonian *ptr, double atol); + +int32_t hamiltonian_equiv(const CHamiltonian *left, + const CHamiltonian *right, + double atol, + uint8_t *out); + +int32_t hamiltonian_is_hermitian(const CHamiltonian *ptr, double atol, uint8_t *out); + +int32_t hamiltonian_get_term(const CHamiltonian *ptr, + size_t index, + CPauliString **out_pauli, + Complex64 *out_coefficient); +``` + +| 接口 | 行为 | +| --- | --- | +| `identity/from_terms` | identity 支持零量子位标量一;空 terms 保留声明宽度。批量构造校验每项宽度和系数、吸收 Pauli 相位、合并重复项,仅删除精确零。 | +| `copy/get_term` | 独立存储副本。get_term 返回项的 Pauli 副本及系数,不自动规范化;Pauli 用 pauli_string_free 释放,零宽度也合法。索引错误为 -2。 | +| `normalized` | 返回经过校验和精确合并的副本,无近零截断。 | +| `normalized_hermitian` | 规范化后将绝对值 ≤1e-10 的虚部投影到零,更大的虚部返回 -8;保留非零实系数。 | +| `add/sub/mul/scaled/adjoint` | 调用 core checked 方法;校验输入与结果系数,非有限值或溢出返回 -8。二元运算要求宽度相同,mul 右侧先作用。 | +| `tensor` | 左侧 ⊗ 右侧,右侧占低位 qubit;宽度相加,溢出返回 -8。 | +| `remap_qubits` | mapping[source]=destination,长度等于输入宽度,目标唯一且小于 target_width;空闲 qubit 填 identity。不是费米模式置换。 | +| `chop` | 原地规范化后删除模长 ≤atol 的系数;失败不修改对象。 | +| `equiv/is_hermitian` | 写入 0/1;atol 有限且非负,0 为精确比较。equiv 要求宽度相同;厄米性检查等价于与伴随比较,不投影系数。 | + +对象结果用 `hamiltonian_free` 释放,输出槽须为空且有效。必需指针为空返回 -1;参数、宽度、系数或容差错误返回 -8;identity、tensor、remap 无法表示的 Pauli 位向量宽度返回 -7。零求和可以保留无需物化的较大声明宽度。 + +atol 是系数容差;规范化后 `is_hermitian` 使用 `2*abs(imag) <= atol`,与 `normalized_hermitian` 的投影阈值是两个独立契约。稀疏代数不构造稠密矩阵,也不隐式调用旧 simplify。 diff --git a/docs/api/cn/c/4_compile/6_decompose_resynthesis.md b/docs/api/cn/c/4_compile/6_decompose_resynthesis.md index 27c0fa92..9f440ee0 100644 --- a/docs/api/cn/c/4_compile/6_decompose_resynthesis.md +++ b/docs/api/cn/c/4_compile/6_decompose_resynthesis.md @@ -1,6 +1,6 @@ # 分解与重综合(C) -本页覆盖线路级分解 pass(电路门定义展开 `decompose_expand_definitions`、矩阵酉门合成 `decompose_unitaries`、多控制门改写 `decompose_mc_gates`)、双比特块重综合 `resynthesize_two_qubit_blocks`、数值酉矩阵合成原语(单比特 / 双比特)、酉合成目标 `decompose_unitary_target_*`、KAK(Weyl)分解、目标门集降级 `target_basis_lowerer_*` 与设备降级 `decompose_lower_to_device`。分解按操作可用的表示分层:定义展开先于数值合成执行,使自带实现线路的酉门在进入矩阵合成之前已经展开。矩阵输入使用 `Complex64`(`{double re; double im}` 交错对,行主序),布局说明见 [酉门](../0_circuit/6_gate_unitary.md)。错误码、字符串与句柄的释放约定遵循 [Overview](../0_overview.md)。 +本页覆盖线路级分解 pass(电路门定义展开 `decompose_expand_definitions`、矩阵酉门合成 `decompose_unitaries`、多控制门改写 `decompose_mc_gates`)、双比特块重综合 `resynthesize_two_qubit_blocks`、数值酉矩阵合成原语(含多比特 Block-ZXZ)、酉合成目标 `decompose_unitary_target_*`、KAK(Weyl)分解、目标门集降级 `target_basis_lowerer_*` 与设备降级 `decompose_lower_to_device`。分解按操作可用的表示分层:定义展开先于数值合成执行,使自带实现线路的酉门在进入矩阵合成之前已经展开。矩阵输入使用 `Complex64`(`{double re; double im}` 交错对,行主序),布局说明见 [酉门](../0_circuit/6_gate_unitary.md)。错误码、字符串与句柄的释放约定遵循 [Overview](../0_overview.md)。 --- @@ -25,13 +25,22 @@ KAK 局域因子标签(`kak_decomposition_local_factor` 的 `factor` 参数) | `KAK_FACTOR_K2L` | 2 | `k2l`(交互之前作用的左侧局域因子)。 | | `KAK_FACTOR_K2R` | 3 | `k2r`(交互之前作用的右侧局域因子)。 | +Block-ZXZ 优化标志(`block_zxz_decompose` 与 `CUnitaryDecomposeConfig.block_zxz_options` 的位掩码): + +| 常量 | 值 | 含义 | +| --- | --- | --- | +| `BLOCK_ZXZ_OPT_A1` | 1 | 在每个递归层吸收两个边界 `CX` 门。 | +| `BLOCK_ZXZ_OPT_A2` | 2 | 在连续双比特叶子之间转移对角余项。 | +| `BLOCK_ZXZ_OPT_A2_FORCE` | 4 | 当 `BLOCK_ZXZ_OPT_A2` 启用时,允许对块对角输入也执行 A.2 优化。 | +| `BLOCK_ZXZ_OPT_ALL` | 3 | 默认优化组合(`BLOCK_ZXZ_OPT_A1 | BLOCK_ZXZ_OPT_A2`),自动处理块对角输入。 | + --- ## 配置构造 ### decompose_unitary_config_default() -按值返回默认酉门分解配置:`recurse_control_flow=1`(递归进入控制流体)。 +按值返回默认酉门分解配置:`recurse_control_flow=1`(递归进入控制流体)、`has_block_zxz_options=1`,且 `block_zxz_options=BLOCK_ZXZ_OPT_ALL`(为三比特及以上酉门启用两项 Block-ZXZ CX 缩减优化)。 ```c struct CUnitaryDecomposeConfig decompose_unitary_config_default(void); @@ -217,6 +226,17 @@ struct CCircuit *resynthesize_two_qubit_blocks(const struct CCircuit *circuit, ## 数值酉合成原语 +### block_zxz_decompose(matrix, dim, atol, options) + +```c +struct CCircuit *block_zxz_decompose(const Complex64 *matrix, uintptr_t dim, + double atol, uint8_t options); +``` + +传入行主序方阵酉矩阵。调用方拥有至少 `dim * dim` 个已初始化且对齐的 `Complex64` 元素(每个元素为实部/虚部双精度浮点数对),`matrix[row * dim + column]` 对应矩阵元素;函数在调用期间借用该缓冲区。`dim` 为矩阵边长,必须是 `[2, 2^20]` 范围内的 2 的幂。接口会在读取前检查字节长度是否溢出,调用方需保证缓冲区覆盖该长度。`atol` 为有限非负绝对容差。 + +`options` 传 `BLOCK_ZXZ_OPT_ALL` 表示默认优化,传 `0` 表示关闭优化,也可按位或组合 `BLOCK_ZXZ_OPT_A1` 与 `BLOCK_ZXZ_OPT_A2`;附加 `BLOCK_ZXZ_OPT_A2_FORCE` 可在启用 A.2 时允许对块对角输入执行该优化。成功时返回拥有所有权且包含全局相位的线路句柄(用 `circuit_free` 释放);空指针、非法维度、长度溢出、未知选项位、非法容差、非有限或非酉矩阵,或数值合成失败时均返回 `NULL`。 + ### synthesize_numeric_1q_unitary(matrix, out) 把 2×2 酉矩阵合成为 Cqlib 的 `U` 门约定:表示的矩阵为 `exp(i * global_phase) * U(theta, phi, lambda)`。`matrix` 指向 4 个行主序 `Complex64` 元素。 @@ -781,14 +801,18 @@ struct CCircuit *decompose_lower_to_device(const struct CCircuit *circuit, ```c typedef struct CUnitaryDecomposeConfig { uint8_t recurse_control_flow; - uint8_t _reserved[7]; + uint8_t has_block_zxz_options; + uint8_t block_zxz_options; + uint8_t _reserved[5]; } CUnitaryDecomposeConfig; ``` | 字段 | 类型 | 含义 | | --- | --- | --- | | `recurse_control_flow` | `uint8_t` | 1 递归进入控制流体,0 不递归。 | -| `_reserved[7]` | `uint8_t[7]` | 填充字段,保持结构体布局稳定。 | +| `has_block_zxz_options` | `uint8_t` | 非 0 时按 `block_zxz_options` 生效;为 0(含全零初始化结构体)时自动使用 `BLOCK_ZXZ_OPT_ALL`。 | +| `block_zxz_options` | `uint8_t` | `has_block_zxz_options != 0` 时应用于三比特及以上 Block-ZXZ 合成的 `BLOCK_ZXZ_OPT_*` 位掩码(默认 `BLOCK_ZXZ_OPT_ALL`)。 | +| `_reserved[5]` | `uint8_t[5]` | 填充字段,保持结构体布局稳定。 | ### CMcGateDecomposeConfig diff --git a/docs/api/cn/c/5_visualization/3_state_plots.md b/docs/api/cn/c/5_visualization/3_state_plots.md index 2cef5286..61851474 100644 --- a/docs/api/cn/c/5_visualization/3_state_plots.md +++ b/docs/api/cn/c/5_visualization/3_state_plots.md @@ -76,6 +76,8 @@ char *plot_state_city_density_matrix(const struct CDensityMatrix *state, 把泡利基期望值绘制为柱状图。标签为 `I`、`X`、`Y`、`Z` 的张量积,共 `4^n` 条,其中 `n` 为量子比特数;非负柱与负值柱使用不同颜色。柱数不超过 `64` 时才绘制旋转的横轴标签。 +默认标签遵循 `PauliString`:最高位在左,qubit 0 在最右侧。例如,两比特态的 `IX` 表示 qubit 0 上的 X。启用 `reverse_bits` 仅反转每个标签中的字符顺序,对应的期望值不变。 + ```c char *plot_state_paulivec(const struct CStatevector *state, const struct CStatePlotOptions *options); diff --git a/docs/api/cn/c/6_error_mitigation/0_overview.md b/docs/api/cn/c/6_error_mitigation/0_overview.md index 4d7e0c1c..08fd7735 100644 --- a/docs/api/cn/c/6_error_mitigation/0_overview.md +++ b/docs/api/cn/c/6_error_mitigation/0_overview.md @@ -56,7 +56,7 @@ typedef void (*CEstimatorFn)(const struct CCircuit *circuit, - **指针有效期**:`circuit`、`hamiltonian` 及全部出参指针仅在回调执行期间有效;回调返回后不得继续使用,也不得保存到回调之外。 - **hamiltonian 所有权**:`hamiltonian` 句柄归库所有,回调不得释放它。回调收到的哈密顿量可能已按流程需要扩展到折叠/拷贝线路的宽度。 -- **出参写入**:回调必须通过 `expectation` 写入期望值;方差已知时写入 `variance`,未知时写入 NaN。虚拟蒸馏的分母电路估计中 `hamiltonian` 为 NULL,回调按无可观测量处理。 +- **出参写入**:回调必须通过 `expectation` 写入期望值;方差已知时写入 `variance`,未知时写入 NaN。虚拟蒸馏的分子与分母估计都会传入非 NULL 的 `hamiltonian`:分子可观测量作用在第 0 份副本的比特上并在辅助比特上携带 `X`,分母可观测量只在辅助比特上携带 `X`(其余比特为恒等)。 - **shots 语义**:`shots` 为 0 表示「未指定」,回调自行决定采样规模;非 0 时为调用方建议的采样数。 回调内部可自由调用模拟器接口(如 [态矢量](../3_qis/1_statevector.md) 的 `statevector_from_circuit` + `statevector_expectation`)完成估计。 diff --git a/docs/api/cn/c/6_error_mitigation/2_virtual_distillation.md b/docs/api/cn/c/6_error_mitigation/2_virtual_distillation.md index b3c6f069..8c1c4d00 100644 --- a/docs/api/cn/c/6_error_mitigation/2_virtual_distillation.md +++ b/docs/api/cn/c/6_error_mitigation/2_virtual_distillation.md @@ -44,11 +44,11 @@ ### virtual_distillation_build_circuit(ptr) -构造虚拟蒸馏协议使用的 copy-swap 线路:先对基底线路做门分解,再把基底线路并排准备 `copies` 份——第 `i` 份整体平移到从 `i × 基底宽度` 开始的比特区间,各份之间互不重叠——最后在首份与其他每一份之间逐比特插入 `SWAP`。 +构造虚拟蒸馏协议使用的 copy-swap 线路(Hadamard-test 线路):先对基底线路做门分解,再把基底线路并排准备 `copies` 份——第 `i` 份整体平移到从 `i × 基底宽度` 开始的比特区间,各份之间互不重叠——然后在末尾的辅助比特(最后一个比特)上施加 `H` 门制备到 `|+⟩`,最后在相邻副本之间施加由辅助比特控制的 `SWAP` 梯(CSWAP),实现各副本的轮换(derangement)。 - `ptr` (`const struct CVirtualDistillation *`):虚拟蒸馏句柄。 -线路宽度为 `copies × 基底宽度`(基底宽度取分解后线路的宽度);操作数为 `copies` 份基底操作加上 `(copies - 1) × 基底宽度` 个 `SWAP`。 +线路宽度为 `copies × 基底宽度 + 1`(基底宽度取分解后线路的宽度,最后一个比特是辅助比特);操作数为 `copies` 份基底操作加上 1 个 `H` 与 `(copies - 1) × 基底宽度` 个受控 `SWAP`。 返回 `struct CCircuit *`:copy-swap 线路的 owned 句柄,用 `circuit_free` 释放;`ptr` 为 NULL 或构造失败时返回 NULL。 @@ -56,11 +56,11 @@ ## 分子与分母 -估计器回调通过 `hamiltonian` 参数区分两种线路:分子线路带可观测量,分母线路无可观测量。 +估计器回调在两种线路上都会收到非 NULL 的 `hamiltonian`,按内容区分:分子可观测量作用在第 0 份副本的比特上并在辅助比特上携带 `X`;分母可观测量只在辅助比特上携带 `X`(其余为恒等)。 ### virtual_distillation_run_numerator_circuit(ptr, hamiltonian, shots, estimator, out_mean, out_variance) -通过估计器回调执行分子线路,估计 `Tr(O ρ^M)`。估计器收到 copy-swap 线路、扩展到 copy-swap 全宽的哈密顿量与 `shots`。扩展规则:原 Pauli 项保持比特索引、相位与系数不变,新增的高索引比特上补 `Z`。 +通过估计器回调执行分子线路,估计 `Tr(O ρ^M)`。估计器收到 copy-swap 线路、扩展到 copy-swap 全宽的哈密顿量与 `shots`。扩展规则:原 Pauli 项保持比特索引(即作用在第 0 份副本上)、相位与系数不变,其余副本补恒等 `I`,并在辅助比特(最后一个比特)上追加 `X`。 - `ptr` (`const struct CVirtualDistillation *`):虚拟蒸馏句柄。 - `hamiltonian` (`const struct CHamiltonian *`):可观测量,比特数须与基底线路宽度一致,构造方式见 [哈密顿量](../3_qis/7_hamiltonian.md)。 @@ -73,7 +73,7 @@ ### virtual_distillation_run_denominator_circuit(ptr, shots, estimator, out_mean, out_variance) -通过估计器回调执行分母线路,估计 `Tr(ρ^M)`。估计器收到 copy-swap 线路、NULL 哈密顿量与 `shots`。 +通过估计器回调执行分母线路,估计 `Tr(ρ^M)`。估计器收到 copy-swap 线路、辅助比特(最后一个比特)上为 `X` 且其余比特为恒等的哈密顿量,以及 `shots`。 - `ptr` (`const struct CVirtualDistillation *`):虚拟蒸馏句柄。 - `shots` (`uintptr_t`):转发给估计器的 shot 数。 @@ -85,7 +85,7 @@ ### virtual_distillation_build_copy_swap_circuit(ptr) -从基底线路构造 copy-swap 线路:先对基底线路做门分解,再把基底线路并排准备 `copies` 份——第 `i` 份整体平移到从 `i × 基底宽度` 开始的比特区间,各份之间互不重叠——最后在首份与其他每一份之间逐比特插入 `SWAP`。线路宽度为 `copies × 基底宽度`(基底宽度取分解后线路的宽度);操作数为 `copies` 份基底操作加上 `(copies - 1) × 基底宽度` 个 `SWAP`。 +从基底线路构造 copy-swap 线路:先对基底线路做门分解,再把基底线路并排准备 `copies` 份——第 `i` 份整体平移到从 `i × 基底宽度` 开始的比特区间,各份之间互不重叠——然后在末尾的辅助比特(最后一个比特)上施加 `H` 门制备到 `|+⟩`,最后在相邻副本之间施加由辅助比特控制的 `SWAP` 梯,实现各副本的轮换。线路宽度为 `copies × 基底宽度 + 1`(基底宽度取分解后线路的宽度);操作数为 `copies` 份基底操作加上 1 个 `H` 与 `(copies - 1) × 基底宽度` 个受控 `SWAP`。 - `ptr` (`const struct CVirtualDistillation *`):虚拟蒸馏句柄。 @@ -119,20 +119,19 @@ #include #include "cqlib_c.h" -/* 分子线路带可观测量,分母线路不带 */ +/* 分子与分母都携带哈密顿量——分子作用在第 0 份副本的比特上并在辅助 + 比特上携带 X,分母只在辅助比特上携带 X;精确模拟线路并求可观测量期望 */ static void estimate(const struct CCircuit *circuit, const struct CHamiltonian *hamiltonian, uintptr_t shots, double *expectation, double *variance) { - if (hamiltonian != NULL) { - *expectation = 1.5; - *variance = 0.25; - } else { - *expectation = 2.0; - *variance = 1.0; - } - (void)circuit; + struct CStatevector *sv = statevector_from_circuit(circuit); + double value = 0.0; + statevector_expectation(sv, hamiltonian, &value); + statevector_free(sv); + *expectation = value; + *variance = 0.0; (void)shots; } @@ -142,13 +141,13 @@ int main(void) { circuit_x(qc, 0); struct CVirtualDistillation *vd = virtual_distillation_new(qc, 2); - /* copy-swap 线路:宽度 = 2 × 1 = 2 */ + /* copy-swap 线路:宽度 = 2 × 1 + 1 = 3 */ struct CCircuit *copy_swap = virtual_distillation_build_circuit(vd); struct CPauliString *z = pauli_string_parse("Z"); struct CHamiltonian *obs = hamiltonian_from_pauli(z); /* takes ownership of z */ - /* mu_vd = 1.5 / 2.0 = 0.75 */ + /* 对 rho = |1><1|:分子 Tr(Z rho^2) = -1,分母 Tr(rho^2) = 1 */ double mean = 0.0, variance = 0.0; virtual_distillation_run_vd(vd, obs, 3, 2, estimate, &mean, &variance); printf("VD estimate: %f\n", mean); diff --git a/docs/api/cn/c/6_error_mitigation/3_unified.md b/docs/api/cn/c/6_error_mitigation/3_unified.md index 858ad020..d1654fdc 100644 --- a/docs/api/cn/c/6_error_mitigation/3_unified.md +++ b/docs/api/cn/c/6_error_mitigation/3_unified.md @@ -72,30 +72,25 @@ ## 示例 -虚拟蒸馏方法的完整流程(分子线路带可观测量、分母线路无可观测量的回调分支,见 [模块概览](0_overview.md)): +虚拟蒸馏方法的完整流程(分子与分母的回调都会收到非 NULL 的哈密顿量,见 [模块概览](0_overview.md)): ```c #include #include "cqlib_c.h" -/* 估计器回调:分子线路带可观测量(精确模拟),分母线路无可观测量 */ +/* 估计器回调:分子与分母都携带哈密顿量(分子作用在第 0 份副本的比特上 + 并在辅助比特上携带 X;分母只在辅助比特上携带 X)——精确模拟线路并求其期望 */ static void estimate(const struct CCircuit *circuit, const struct CHamiltonian *hamiltonian, uintptr_t shots, double *expectation, double *variance) { - if (hamiltonian != NULL) { - struct CStatevector *sv = statevector_from_circuit(circuit); - double value = 0.0; - statevector_expectation(sv, hamiltonian, &value); - statevector_free(sv); - *expectation = value; - *variance = 0.0; - } else { - /* 分母 Tr(rho^M):由采样型估计器从测量结果估计,此处返回示例值 */ - *expectation = 1.0; - *variance = 0.0; - } + struct CStatevector *sv = statevector_from_circuit(circuit); + double value = 0.0; + statevector_expectation(sv, hamiltonian, &value); + statevector_free(sv); + *expectation = value; + *variance = 0.0; (void)shots; } diff --git a/docs/api/cn/python/0_circuit/0_overview.md b/docs/api/cn/python/0_circuit/0_overview.md index b7caf528..c4e513f7 100644 --- a/docs/api/cn/python/0_circuit/0_overview.md +++ b/docs/api/cn/python/0_circuit/0_overview.md @@ -111,6 +111,7 @@ print(bound.used_symbols) # [] | `ClassicalVar` | [Classical / Control Flow](9_classical_control_flow.md) | 可变经典存储句柄,由 `Circuit.var()` 创建。 | | `ClassicalValue` | [Classical / Control Flow](9_classical_control_flow.md) | 不可变经典值,通常由测量产生。 | | `Measurement` | [Classical / Control Flow](9_classical_control_flow.md) | 测量回执,包含测量值和被测量的量子比特顺序。 | +| `ClassicalDataOp` | [Classical / Control Flow](9_classical_control_flow.md) | 经典数据操作的指令形式(变量写入或测量结果写入),通过 `Instruction.classical_data` 获得。 | | `ClassicalExpr` | [Classical / Control Flow](9_classical_control_flow.md) | 类型化经典表达式 AST,用于条件、比较、位抽取和表达式组合。 | | `ClassicalControlOp` | [Classical / Control Flow](9_classical_control_flow.md) | 结构化控制流 IR,包含 `if`、`while`、`for`、`switch`、`break` 和 `continue`。 | | `ValueControlBody` | [Classical / Control Flow](9_classical_control_flow.md) | 构造层控制流体,包含若干 `ValueOperation`。 | diff --git a/docs/api/cn/python/0_circuit/4_operation_instruction.md b/docs/api/cn/python/0_circuit/4_operation_instruction.md index 868dd572..f1dd7e98 100644 --- a/docs/api/cn/python/0_circuit/4_operation_instruction.md +++ b/docs/api/cn/python/0_circuit/4_operation_instruction.md @@ -71,7 +71,13 @@ delay_inst = Instruction.delay() | `is_classical_data` | `bool` | 是否为经典数据相关指令。 | | `is_delay` | `bool` | 是否为延迟指令。 | | `standard_gate` | `StandardGate / None` | 当指令为标准门时,返回内部标准门对象。 | +| `mc_gate` | `MCGate / None` | 当指令为多控制门时,返回内部 `MCGate` 对象。 | +| `unitary_gate` | `UnitaryGate / None` | 当指令为用户自定义酉门时,返回内部 `UnitaryGate` 对象。 | +| `circuit_gate` | `CircuitGate / None` | 当指令为子线路复合门时,返回内部 `CircuitGate` 对象。 | | `directive` | `Directive / None` | 当指令为 `Directive` 时,返回内部 directive 对象。 | +| `classical_data` | `ClassicalDataOp / None` | 当指令为经典数据操作时,返回内部 `ClassicalDataOp` 对象。 | + +这些 payload 访问器返回的门对象不携带绑定参数:参数属于 operation 层(见 `ValueOperation.params`),返回门的参数列表恒为空。注意 `Instruction` 不提供 `classical_control` payload 访问器:存储层控制流操作内联了线路内部句柄,其内容只能在构造层通过 `ValueInstruction.classical_control` 读取。 --- @@ -98,7 +104,11 @@ delay_inst = Instruction.delay() | `instruction_type` | `str` | 指令类别,取值与 `Instruction.instruction_type` 一致;包裹控制流时为 `"classical_control"`。 | | `is_standard` / `is_mcgate` / `is_unitary` / `is_circuit_gate` / `is_directive` / `is_classical_data` / `is_delay` | `bool` | 与 `Instruction` 同名的类别判定属性;包裹控制流时均为 `False`。 | | `standard_gate` | `StandardGate / None` | 当包裹的是标准门指令时,返回内部标准门对象。 | +| `mc_gate` | `MCGate / None` | 当包裹的是多控制门指令时,返回内部 `MCGate` 对象。 | +| `unitary_gate` | `UnitaryGate / None` | 当包裹的是用户自定义酉门指令时,返回内部 `UnitaryGate` 对象。 | +| `circuit_gate` | `CircuitGate / None` | 当包裹的是子线路复合门指令时,返回内部 `CircuitGate` 对象。 | | `directive` | `Directive / None` | 当包裹的是 `Directive` 指令时,返回内部 directive 对象。 | +| `classical_data` | `ClassicalDataOp / None` | 当包裹的是经典数据指令时,返回内部 `ClassicalDataOp` 对象。 | --- diff --git a/docs/api/cn/python/0_circuit/9_classical_control_flow.md b/docs/api/cn/python/0_circuit/9_classical_control_flow.md index 41926948..3fabfe58 100644 --- a/docs/api/cn/python/0_circuit/9_classical_control_flow.md +++ b/docs/api/cn/python/0_circuit/9_classical_control_flow.md @@ -5,6 +5,7 @@ - `cqlib.circuit.ClassicalVar` - `cqlib.circuit.ClassicalValue` - `cqlib.circuit.Measurement` +- `cqlib.circuit.ClassicalDataOp` - `cqlib.circuit.ClassicalExpr` - `cqlib.circuit.ClassicalControlOp` - `cqlib.circuit.ValueControlBody` @@ -15,6 +16,7 @@ from cqlib.circuit import ( CircuitId, ClassicalType, ClassicalExpr, + ClassicalDataOp, ClassicalControlOp, ValueControlBody, ValueSwitchCase, @@ -35,6 +37,7 @@ from cqlib.circuit import ( | `ClassicalVar` | 可变经典变量句柄,由 `Circuit.var()` 创建。 | | `ClassicalValue` | 不可变经典值句柄,通常由测量产生。 | | `Measurement` | 测量回执,记录测量结果句柄和被测量的量子比特顺序。 | +| `ClassicalDataOp` | 经典数据操作的指令形式(变量写入或测量结果写入),通过 `Instruction.classical_data` 获得。 | | `ClassicalExpr` | 无副作用的经典表达式,可表示字面量、变量读取、比较和逻辑组合。 | | `ClassicalControlOp` | 低层控制流对象,用于表示 `if`、`while`、`for`、`switch`、`break` 和 `continue`。 | | `ValueControlBody` | 控制流分支体或循环体中的操作序列。 | @@ -238,6 +241,30 @@ condition = single.expr().to_bool() --- +## `ClassicalDataOp` + +`ClassicalDataOp` 是经典数据操作的指令形式:写入可变经典变量,或产生不可变经典值的测量。它不直接构造,实例通过 `Instruction` 或 `ValueInstruction` 的 `classical_data` 属性获得。 + +| 属性 | 类型 | 说明 | +|---|---|---| +| `kind` | `str` | 操作类别:`"store"`、`"measure_bit"` 或 `"measure_bits"`。 | +| `target` | `ClassicalVar / None` | 当 `kind` 为 `"store"` 时,返回写入的目标变量。 | +| `value` | `ClassicalExpr / None` | 当 `kind` 为 `"store"` 时,返回写入的表达式。 | +| `result` | `ClassicalValue / None` | 当 `kind` 为 `"measure_bit"` 或 `"measure_bits"` 时,返回接收结果的不可变值。 | + +```python +from cqlib import Circuit + +circuit = Circuit(2) +circuit.measure_bits([0, 1]) + +data = circuit.operations[0].instruction.classical_data +print(data.kind) # measure_bits +print(data.result) # 测量产生的 ClassicalValue +``` + +--- + ## `ClassicalExpr` `ClassicalExpr` 它用于描述经典计算关系,如读取变量、读取测量值、构造字面量、执行逻辑运算、比较表达式、条件选择、位抽取和位拼接。 @@ -618,4 +645,4 @@ circuit = Circuit(1) circuit.if_(ClassicalExpr.bool_literal(True), lambda body: body.compose(branch)) ``` -这种方式可以将“量子门级验证”和“控制流结构构造”分开处理,使测试和调试过程更加清晰。 \ No newline at end of file +这种方式可以将“量子门级验证”和“控制流结构构造”分开处理,使测试和调试过程更加清晰。 diff --git a/docs/api/cn/python/1_ir/3_qasm3.md b/docs/api/cn/python/1_ir/3_qasm3.md index fd53bcb8..e2ba59d8 100644 --- a/docs/api/cn/python/1_ir/3_qasm3.md +++ b/docs/api/cn/python/1_ir/3_qasm3.md @@ -143,6 +143,7 @@ circuit = qasm3.loads(code) - 子程序与外部调用:`def` 子程序、`extern` - 硬件相关:硬件量子比特、`output` 声明,以及除角度与浮点以外的 `input` 声明 - 其它语句:`alias`、`pragma`、注解、旧式声明 +- 程序终止:`end`;任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 - 门修饰符:`negctrl`、`pow`;`ctrl` 与 `inv` 仅在目标门存在对应实现时可用 - 部分标准门:`ch`、`cp`、`cu`、`cswap` - 控制流:`while` 在实现中存在下降路径,但运行时条件的循环当前会被语义检查拒绝;`for` 只支持范围为常量的静态展开形式 diff --git a/docs/api/cn/python/3_qis/0_overview.md b/docs/api/cn/python/3_qis/0_overview.md index 9339a0b1..fb3f4aba 100644 --- a/docs/api/cn/python/3_qis/0_overview.md +++ b/docs/api/cn/python/3_qis/0_overview.md @@ -29,6 +29,8 @@ ### 观测量与时间演化 +[`FermionicOp` 与 `JordanWignerMapper`](10_fermion.md) 提供通用费米代数、激发生成元及费米到 Pauli 和的映射,可直接复用现有演化组件。 + `PauliString` 与 `Hamiltonian` 描述可观测量,两者都可以给出期望值;`Hamiltonian` 还可以通过 Trotter 分解转成演化线路,回到 `cqlib.circuit` 的线路空间中执行。 --- diff --git a/docs/api/cn/python/3_qis/10_fermion.md b/docs/api/cn/python/3_qis/10_fermion.md new file mode 100644 index 00000000..15670693 --- /dev/null +++ b/docs/api/cn/python/3_qis/10_fermion.md @@ -0,0 +1,72 @@ +# 费米算子与 Jordan–Wigner 映射 + +`cqlib.qis.fermion` 提供通用费米代数与稀疏映射。公共类型也可以从 `cqlib.qis` 导入,计算由 Rust Core 完成。 + +```python +from cqlib.qis import FermionicLadder, FermionicOp, JordanWignerMapper + +a = FermionicOp.annihilation(num_modes=4, mode=0) +identity = FermionicOp.identity(4) +assert (a * a.adjoint() + a.adjoint() * a).equiv(identity) + +term = [FermionicLadder.create(2), FermionicLadder.annihilate(0)] +op = FermionicOp.from_term(num_modes=4, term=term, coefficient=0.5j) +hamiltonian = JordanWignerMapper().map_operator(op) +``` + +## 算子与运算 + +`FermionicLadder.create(mode)` 和 `annihilate(mode)` 创建不可变单算子,提供只读 `mode`、`kind`、`adjoint()`、值比较和哈希。它自身不声明模态空间,越界检查发生在构造 `FermionicOp` 时。 + +`FermionicOp(num_modes)` 创建零算子;`identity(num_modes)` 创建恒等算子。`from_term(num_modes, term, coefficient=1.0)` 接受一个有序乘积;`from_terms(num_modes, terms)` 接受 `(term, coefficient)` 二元组的可迭代对象,合并重复项。空乘积是恒等项,空项集合是零算子,二者都保留模态数量,包括零模态。 + +| 接口 | 行为 | +| --- | --- | +| `creation` / `annihilation` / `number` | 参数为 `num_modes, mode`;构造产生、湮灭、模态数算子。 | +| `total_number(num_modes)` | 构造总粒子数算子。 | +| `A + B` / `A - B` / `-A` | 返回新算子;加减要求模态数量一致。 | +| `A * B` | 算子乘积 AB,B 先作用;不自动正规序。 | +| `c * A` / `A * c` / `A.scaled(c)` | 标量乘法,接受有限的整数、浮点数和复数。 | +| `adjoint()` | 共轭系数、反转乘积并交换产生与湮灭。 | +| `normal_order()` | 返回新展开:产生算子在前,每组模态编号升序,保留收缩项与符号。 | +| `add_term(term, coefficient=1.0)` | 原地添加项;失败后对象不变,返回 `None`。 | +| `chop(*, atol=0.0)` | 原地删除复模长不大于容差的项,返回 `None`。 | +| `equiv(other, *, atol=0.0)` | 正规序后判断代数等价,模态数量不一致报错。 | +| `is_hermitian(*, atol=0.0)` | 判断算子与其共轭转置是否代数等价。 | + +只读属性 `num_modes`、`num_terms` 描述存储;`terms` 返回独立的 `list[(tuple[FermionicLadder, ...], complex)]` 快照。`==` 比较存储结构,`is_zero()` 检查存储为空;数学等价与代数零使用 `equiv()` 判断。 + +默认只删除精确零,不隐式截断微小系数。容差必须有限且非负。`copy()`、`copy.copy()`、`copy.deepcopy()` 创建独立副本。算子可变且不可哈希;`A += B` 重新绑定结果,不修改 A 的别名。求和使用 `sum(operators, start=FermionicOp(num_modes))`。 + +## 激发生成元与演化 + +`excitation_generator(num_modes, sources, targets)` 构造 G = i(T − T†)。T 的产生算子按 targets 原顺序排列,湮灭算子按 sources 逆序排列。例如 `[0, 1] -> [2, 3]` 表示 T = a†₂ a†₃ a₁ a₀。列表必须非空、等长、各自无重复且互不重叠;不自动排序,也不引入阶乘归一化。 + +```python +from cqlib.circuit.ansatz import BasisEncoding, EvolutionStrategy, PauliEvolutionAnsatz + +mapper = JordanWignerMapper() +circuit = BasisEncoding(mapper.map_occupation([1, 1, 0, 0])).build_circuit("hf") +for name, sources, targets in [ + ("theta_double", [0, 1], [2, 3]), + ("theta_single", [0], [2]), +]: + generator = FermionicOp.excitation_generator(4, sources, targets) + block = (PauliEvolutionAnsatz(mapper.map_operator(generator)) + .with_strategy(EvolutionStrategy.exact()) + .with_time_param_name(name).build_circuit("excitation")) + circuit.compose(block) +bound = circuit.assign_parameters({"theta_double": 0.2, "theta_single": -0.3}) +``` + +每块演化为 exp(−iθG) = exp(θ(T − T†))。多个独立参数应分别构造、命名并组合演化块;把生成元相加后构造一块演化会共享一个参数。 + +## 映射与扩展 + +`JordanWignerMapper()` 提供 `map_operator(op) -> Hamiltonian`、`num_qubits(num_modes) -> int` 和 `map_occupation(occupation) -> list[bool]`。算子映射支持非厄米、恒等和零算子;线路与期望值消费者自行要求厄米性。 + +模态从 0 编号,模态 p 对应比特 p,Z 链覆盖小于 p 的编号,比特 0 是最低有效位。占据输入必须为整数 0/1 或布尔值;返回 `bits[p]` 对应比特 p,空输入返回空列表。Core 不规定 α/β 或化学轨道顺序。 + +`FermionToQubitMapper` 与 `OccupationStateMapper` 是独立的、可运行时检查的 `typing.Protocol`。开发者可以实现同签名的方法,不必继承协议;运行时检查只确认成员存在,不验证签名和计算正确性。Python 映射器由算法代码直接调用,不自动桥接到 Rust trait。 + +类型错误抛出 `TypeError`;负数或越界模态抛出 `IndexError`;负模态数量、空间不匹配、非有限系数、非法占据值或容差抛出 `ValueError`;模态整数超出 Rust 可表示范围抛出 `OverflowError`。 diff --git a/docs/api/cn/python/3_qis/1_statevector.md b/docs/api/cn/python/3_qis/1_statevector.md index 15445836..1e9f91fd 100644 --- a/docs/api/cn/python/3_qis/1_statevector.md +++ b/docs/api/cn/python/3_qis/1_statevector.md @@ -20,6 +20,8 @@ from cqlib.qis.state import Statevector ### Statevector(num_qubits) +状态维度无法表示或状态内存分配失败时抛出 `ValueError`。支持零比特状态。 + 创建一个处于 |0…0⟩ 的状态。 参数: diff --git a/docs/api/cn/python/3_qis/2_density_matrix.md b/docs/api/cn/python/3_qis/2_density_matrix.md index 1b053966..8588a82c 100644 --- a/docs/api/cn/python/3_qis/2_density_matrix.md +++ b/docs/api/cn/python/3_qis/2_density_matrix.md @@ -20,6 +20,8 @@ from cqlib.qis.state import DensityMatrix ### DensityMatrix(num_qubits) +状态维度无法表示或状态内存分配失败时抛出 `ValueError`。支持零比特状态。 + 创建一个处于 |0…0⟩⟨0…0| 的纯态。 参数: diff --git a/docs/api/cn/python/3_qis/3_density_matrix_noise.md b/docs/api/cn/python/3_qis/3_density_matrix_noise.md index a2ec8681..331ac71c 100644 --- a/docs/api/cn/python/3_qis/3_density_matrix_noise.md +++ b/docs/api/cn/python/3_qis/3_density_matrix_noise.md @@ -21,6 +21,8 @@ from cqlib.qis.state import DensityMatrixNoise ### DensityMatrixNoise(num_qubits, noise_model=None) +状态维度无法表示或状态内存分配失败时抛出 `ValueError`。支持零比特状态。 + 创建一个模拟器。省略噪声模型时等价于理想模拟。 参数: @@ -169,7 +171,7 @@ assert sim.state[0, 0] != 999.0 **概率** - `probabilities() -> list[float]`:返回不含读出噪声的各基态概率,长度为 2^num_qubits。不修改状态。 -- `probabilities_with_readout(qubits) -> list[float]`:返回在指定比特上施加读出噪声后的概率分布,长度为 2^n,n 为 `qubits` 长度。 +- `probabilities_with_readout(qubits) -> list[float]`:`qubits` 为施加读出误差的存储位置;绑定线路后,按这些位置对应的线路比特 ID 查询噪声模型,未绑定时 ID 与位置相同。返回完整的 `2^num_qubits` 项概率数组,保持存储位序,不随选择的顺序或数量改变;空选择不施加读出误差。位置越界时抛出 `IndexError`,即使未配置噪声模型。 - `qubits` (`list[int]`):参与读出噪声建模的比特下标列表。下标越界时抛出 `IndexError`。 **测量与采样** diff --git a/docs/api/cn/python/3_qis/7_hamiltonian.md b/docs/api/cn/python/3_qis/7_hamiltonian.md index 8e5627ee..fd09bb46 100644 --- a/docs/api/cn/python/3_qis/7_hamiltonian.md +++ b/docs/api/cn/python/3_qis/7_hamiltonian.md @@ -99,6 +99,7 @@ class Observable(Protocol): - `to_trotter_circuit(time, steps, mode) -> Circuit`:生成 Trotter-Suzuki 分解给出的时间演化线路,用一串 Pauli 旋转逼近 $U(t) = e^{-iHt}$。 - `to_evolution_circuit(time, steps, mode) -> Circuit`:生成时间演化线路。所有项对易时走精确的单遍分解;存在非对易项时回退到指定的 Trotter 模式与步数。 - `copy() -> Hamiltonian`:返回副本。 +- 标准库 `copy.copy(h)` 和 `copy.deepcopy(h)` 同样返回项数据独立的副本。 - `expectation_statevector(sv) -> float`:由态矢量计算期望值。 - `expectation_density_matrix(dm) -> float`:由密度矩阵计算期望值。 - `expectation_probs(measurements) -> float`:由测量概率计算期望值。 @@ -113,6 +114,8 @@ class Observable(Protocol): ### 异常情况 +实数期望值和方差接口要求吸收 Pauli 相位、合并重复项后的算符为厄米算符;原始及合并后的系数必须有限,否则抛出 `ValueError`。计算保留非零小系数。 + - `ValueError`:两个算符比特数不一致(`+`、`+=`)、项的比特数与算符不一致(`from_list`、`add_term`)、系数类型不受支持、观测量与量子态比特数不一致(`expectation_*`、`variance_statevector`)、测量概率中找不到可用的测量基(`expectation_probs`)。 - `ValueError`:`to_trotter_circuit` 与 `to_evolution_circuit` 在 `steps` 为 `0`、算符为空、系数非 Hermitian、或 Pauli 字符串相位非 Hermitian 时抛出。 @@ -220,3 +223,39 @@ assert trotterized.num_qubits == 1 | `ValueError` | `expectation_probs` 无法从给定的测量基推出待求算符。 | 观测量计算的输入类型见 [Statevector](1_statevector.md) 与 [DensityMatrix](2_density_matrix.md);Trotter 模式的定义见 [Trotter 演化](8_evolution.md)。 + +## 经过校验的稀疏代数 + +`from_terms(num_qubits, terms)` 明确指定宽度,接受 `(PauliString, 整数/浮点数/复数)` 项。它校验尺寸与有限系数、吸收 Pauli 相位并合并重复项,只删除精确零;空输入保留指定宽度。 + +| 接口 | 行为 | +| --- | --- | +| `normalized()` | 返回校验与合并后的新对象,保留所有非零系数。 | +| `add(other)` | 同宽度的安全加法,返回合并后的新对象。 | +| `A - B`、`A * B`、`-A` | 安全减法、算子乘积及取负;AB 中 B 先作用。 | +| `c * A`、`A * c`、`scaled(c)` | 校验标量及结果系数,返回新对象。 | +| `adjoint()` | 返回共轭转置,包括 Pauli 相位。 | +| `chop(*, atol=0.0)` | 原地规范化,并删除复模长不大于容差的系数;失败后对象不变。 | +| `equiv(other, *, atol=0.0)` | 比较规范化后的系数差,宽度不一致报错;容差不是矩阵算子范数界。 | +| `is_hermitian(*, atol=0.0)` | 与共轭转置比较,即规范化系数满足 2·abs(imag) ≤ atol。 | +| `normalized_hermitian()` | 将模长不大于 1e-10 的虚部残差投影为零,更大虚部报错;保留任意非零实部。 | +| `tensor(other)` | 返回 self ⊗ other,other 占低编号比特。 | +| `remap_qubits(mapping, target_width)` | mapping[source] = destination;目标必须唯一且在范围内,未使用位置补恒等。 | + +这些接口支持非厄米算子,厄米性由演化与期望值消费者校验。所有容差必须有限且非负。比特嵌入是量子比特重标记,不是费米模态置换。 + +```python +from cqlib.qis import Hamiltonian, PauliString + +x = Hamiltonian.from_terms(1, [(PauliString.from_str("X"), 1.0)]) +z = Hamiltonian.from_terms(1, [(PauliString.from_str("Z"), 1.0)]) +assert (x * z).equiv(Hamiltonian.from_terms(1, [(PauliString.from_str("Y"), -1j)])) +assert x.add(x).equiv(2 * x) +assert x.remap_qubits([2], target_width=3).num_qubits == 3 +``` + +### 旧接口兼容 + +`from_list`、`add_term`、`scale`、`+`、`+=` 保留现有行为。其中 `+` 与 `+=` 拼接存储项;`scale` 原地缩放。`simplify()` 使用旧的近零截断策略,会删除微小系数。需要完整保留映射结果时使用 `normalized()`,需要明确截断时使用 `chop(atol=...)`。 + +`add_term()` 和 `scale()` 原地修改并返回 `None`,不支持链式调用。新代数运算遇到宽度不一致、非有限系数或中间系数溢出时抛出 `ValueError`。 diff --git a/docs/api/cn/python/3_qis/9_metrics_entropy.md b/docs/api/cn/python/3_qis/9_metrics_entropy.md index 70ed16c9..aa976528 100644 --- a/docs/api/cn/python/3_qis/9_metrics_entropy.md +++ b/docs/api/cn/python/3_qis/9_metrics_entropy.md @@ -370,6 +370,8 @@ assert abs(entropy.linear_entropy(dm_pure) - 0.0) < 1e-10 ### `renyi_entropy(dm, alpha) -> float` +阶数必须为正且不能为 NaN。`alpha = 1` 返回冯·诺依曼熵,正无穷返回最小熵;接近 1 时使用稳定计算。非对角矩阵中不超过 `矩阵维度 × f64::EPSILON × 最大特征值` 的特征值视为数值零;对角矩阵保留全部正特征值。 + 计算阶数为 `alpha` 的 Rényi 熵。 参数: @@ -383,7 +385,7 @@ assert abs(entropy.linear_entropy(dm_pure) - 0.0) < 1e-10 异常情况: -- `ValueError`:`alpha` 不大于零,或特征分解失败。 +- `ValueError`:`alpha` 为 NaN 或不大于零,或特征分解失败。 示例: @@ -528,7 +530,7 @@ assert abs(entropy.entanglement_of_formation(dm_sep) - 0.0) < 1e-10 | 异常 | 触发场景 | | --- | --- | -| `ValueError` | 参与比较的两个量子态比特数不一致;`renyi_entropy` 的 `alpha` 不大于零;`entanglement_entropy_pure` 的子系统为空、包含全部比特或含重复下标;`concurrence` 与 `entanglement_of_formation` 的态不是 2 比特;特征分解失败。 | +| `ValueError` | 参与比较的两个量子态比特数不一致;`renyi_entropy` 的 `alpha` 为 NaN 或不大于零;`entanglement_entropy_pure` 的子系统为空、包含全部比特或含重复下标;`concurrence` 与 `entanglement_of_formation` 的态不是 2 比特;特征分解失败。 | | `IndexError` | `partial_transpose`、`logarithmic_negativity`、`negativity`、`entanglement_entropy_pure` 的比特下标越界。 | 注意 `cqlib.qis.entropy` 是子模块名,`cqlib.qis.metrics` 中另有一个同名函数 `entropy`,二者互不相干。 diff --git a/docs/api/cn/python/4_compile/6_decompose_resynthesis.md b/docs/api/cn/python/4_compile/6_decompose_resynthesis.md index 56b9f9bc..762c66bc 100644 --- a/docs/api/cn/python/4_compile/6_decompose_resynthesis.md +++ b/docs/api/cn/python/4_compile/6_decompose_resynthesis.md @@ -61,7 +61,7 @@ from cqlib.compile.transform import DeviceLowerer ### decompose_unitaries(circuit, config=None) -用矩阵合成单比特与双比特酉门。 +合成线路中带固定数值矩阵的酉门。三比特及以上的门在路由与目标门集转换之前使用 Block-ZXZ 合成。 参数: @@ -84,13 +84,14 @@ from cqlib.compile.transform import DeviceLowerer - `(TransformResult, DecompositionRuleStats)` -### UnitaryDecomposeConfig(*, two_qubit_basis=None, target_basis=None, recurse_control_flow=True) +### UnitaryDecomposeConfig(*, two_qubit_basis=None, target_basis=None, recurse_control_flow=True, block_zxz_options=None) 参数: - `two_qubit_basis` (`TwoQubitUnitaryDecomposeBasis | None`):双比特合成门集。 - `target_basis` (`list[str | Instruction] | None`):目标门集约束,条目形式同 `compile()` 的 `target_basis`。 - `recurse_control_flow` (`bool`):是否递归进入控制流块。 +- `block_zxz_options` (`BlockZxzDecomposeOptions | None`):应用于三比特及以上 Block-ZXZ 合成的优化开关;`None` 表示使用 `BlockZxzDecomposeOptions()`。 `two_qubit_basis` 与 `target_basis` 互斥,同时给出会被拒绝。 @@ -99,6 +100,7 @@ from cqlib.compile.transform import DeviceLowerer - `two_qubit_basis -> TwoQubitUnitaryDecomposeBasis | None` - `target_basis -> list[Instruction] | None` - `recurse_control_flow -> bool` +- `block_zxz_options -> BlockZxzDecomposeOptions` 异常情况: @@ -124,6 +126,24 @@ pass 内规则缓存统计: --- +## Block-ZXZ 合成 + +```python +from cqlib.compile.transform.decompose import ( + BlockZxzDecomposeOptions, + decompose_block_zxz, + decompose_block_zxz_with_options, +) + +circuit = decompose_block_zxz(matrix, atol=1e-10) +options = BlockZxzDecomposeOptions(opt_a1=True, opt_a2=True, opt_a2_force=False) +circuit = decompose_block_zxz_with_options(matrix, atol=1e-10, options=options) +``` + +两个函数均接收形状为 `(2**n, 2**n)`(`n >= 1`)的有限酉矩阵数组,返回 `to_matrix()` 包含原始全局相位的 `Circuit`。局部比特 0 为矩阵最低有效位。`atol` 为有限非负绝对容差,用于校验输入酉性(`||M†M - I||_max <= atol`)并控制解复用器和双比特叶子的重构误差;通过输入校验的近酉矩阵会在需要时先投影到所有酉不变范数下最近的精确酉矩阵 `U_proj`,再以 `atol` 为容差重构 `U_proj`。非法矩阵值、维度或容差会抛出 `CompilerConfigError`;数值合成失败会抛出 `CompilerTransformError`。 + +A.1 在每个递归节点吸收两个边界 CX 门;A.2 在双比特叶子之间转移对角余项;两者默认开启。对于块对角输入,除非显式强制(`opt_a2_force=True`),否则默认关闭 A.2。`BlockZxzDecomposeOptions.none()` 可同时关闭两项优化。对于三比特及以上输入,精确块对角矩阵仅使用单个解复用器;若上下两半相等,最高位比特保持空闲。若某个双比特 KAK 叶子无法达到请求精度,合成器会针对原始 4×4 矩阵额外检查一层 Block-ZXZ 回退。一般三比特和四比特情况最多分别达到 19 个和 95 个 CX 门;数值回退可能会增加门数并保持完整矩阵精度。 + ## 数值酉门合成 `cqlib.compile.transform.decompose.unitary` 提供矩阵到门序列的直接合成,不经过线路遍历。 diff --git a/docs/api/cn/python/5_visualization/3_state_plots.md b/docs/api/cn/python/5_visualization/3_state_plots.md index 2bff0705..d563bd04 100644 --- a/docs/api/cn/python/5_visualization/3_state_plots.md +++ b/docs/api/cn/python/5_visualization/3_state_plots.md @@ -120,6 +120,8 @@ assert plot_state_paulivec(state) == plot_state_paulivec(density) 计算量子态在 Pauli 基下的期望值,并渲染成柱状图。 +默认标签遵循 `PauliString`:最高位在左,qubit 0 在最右侧。例如,两比特态的 `IX` 表示 qubit 0 上的 X。启用 `reverse_bits` 仅反转每个标签中的字符顺序,对应的期望值不变。 + 参数: - `state` (`QuantumState`):待渲染的量子态。 diff --git a/docs/api/cn/python/6_error_mitigation/0_overview.md b/docs/api/cn/python/6_error_mitigation/0_overview.md index 189df655..6b0f433c 100644 --- a/docs/api/cn/python/6_error_mitigation/0_overview.md +++ b/docs/api/cn/python/6_error_mitigation/0_overview.md @@ -30,7 +30,7 @@ 两种方法都不直接执行输入线路,而是先构造一族缓解线路: - 零噪声外推按折叠等级展开线路。全局折叠把线路改写为 `U -> U (U† U)^level`,使线路深度随等级增长;选择性折叠只对指令名匹配给定门集的操作执行同样的展开,其余操作原样保留。等级为 `0` 时缓解线路即输入线路的副本。 -- 虚拟蒸馏把线路复制 `copies` 份并按位插入 SWAP,得到一条宽度为 `copies` 倍的 copy-swap 线路。分子与分母在同一线路上执行,区别只在传给回调的观测量:分母为 `None`,分子为按拷贝数扩展后的 `Hamiltonian`。 +- 虚拟蒸馏把线路复制 `copies` 份,追加一个经 Hadamard 门制备到 `|+⟩` 的辅助比特,并在相邻副本之间按位施加由辅助比特控制的 SWAP,得到一条宽度为 `copies` 倍再加 1 的 copy-swap 线路。分子与分母在同一线路上执行,区别只在传给回调的观测量:分子为扩展到全宽的 `Hamiltonian`(第 0 份副本上的原观测量 ⊗ 辅助比特上的 `X`),分母为仅辅助比特上带 `X` 的 `Hamiltonian`。 ### 数据流 @@ -104,9 +104,9 @@ print("variance:", result.variance) | **选择性折叠** | 只对指令名匹配 `gate_set` 的操作做折叠,其余操作原样保留。 | | **外推方法** | 把不同噪声因子下的期望值外推到零噪声点的拟合模型,包括多项式与指数两种。 | | **拷贝数** | 虚拟蒸馏中密度矩阵的拷贝份数,由 `copies` 给出,最小为 2。 | -| **copy-swap 线路** | 由输入线路复制 `copies` 份并按位插入 SWAP 得到的缓解线路。 | -| **分子线路** | 用于估计 `Tr(O ρ^M)` 的 copy-swap 线路执行,观测量为按拷贝数扩展后的 `Hamiltonian`。 | -| **分母线路** | 用于估计 `Tr(ρ^M)` 的 copy-swap 线路执行,观测量为 `None`。 | +| **copy-swap 线路** | 由输入线路复制 `copies` 份、追加一个经 Hadamard 门制备的辅助比特、并在相邻副本之间按位施加辅助比特控制的 SWAP 得到的缓解线路。 | +| **分子线路** | 用于估计 `Tr(O ρ^M)` 的 copy-swap 线路执行,观测量为扩展到全宽的 `Hamiltonian`(第 0 份副本上的原观测量 ⊗ 辅助比特上的 `X`)。 | +| **分母线路** | 用于估计 `Tr(ρ^M)` 的 copy-swap 线路执行,观测量为辅助比特上的 `X`(其余比特为恒等)。 | | **estimator** | 调用方提供的回调,执行一条缓解线路并返回 `(期望值, 方差)` 二元组。 | | **统一流水线** | 由 `ErrorMitigation` 承载的顺序式流程:`run()` 收集估计值,`get_mitigated()` 做后处理。 | @@ -190,13 +190,20 @@ hamiltonian = Hamiltonian.from_list([(PauliString.from_str("Z"), 1.0)]) vd = VirtualDistillation(circuit, 2) copy_swap = vd.build_copy_swap_circuit() -print(copy_swap.width) # 2 +print(copy_swap.width) # 3 = copies * 基础宽度 + 1 def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) # 分母:Tr(ρ^M) - return (1.5, 0.25) # 分子:Tr(O ρ^M) + # 分子与分母都携带观测量:分子在第 0 份副本的比特上有非恒等 Pauli, + # 分母只有辅助比特(最后一个比特)上的 X + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) # 分子:Tr(O ρ^M) + return (2.0, 1.0) # 分母:Tr(ρ^M) expectation, variance = vd.run_vd( @@ -229,9 +236,14 @@ hamiltonian = Hamiltonian.from_list([(PauliString.from_str("Z"), 1.0)]) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) - return (1.5, 0.25) + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) + return (2.0, 1.0) mitigation = ErrorMitigation( diff --git a/docs/api/cn/python/6_error_mitigation/2_virtual_distillation.md b/docs/api/cn/python/6_error_mitigation/2_virtual_distillation.md index 88b2c8bd..f6ae5794 100644 --- a/docs/api/cn/python/6_error_mitigation/2_virtual_distillation.md +++ b/docs/api/cn/python/6_error_mitigation/2_virtual_distillation.md @@ -2,7 +2,7 @@ `cqlib.error_mitigation.virtual_distillation` -`cqlib.error_mitigation.virtual_distillation` 提供虚拟蒸馏的低层接口:把基础线路复制若干份并插入 SWAP 构造 copy-swap 线路,再分别估计分子与分母,最后求比值得到缓解后的期望值。本页覆盖 `VirtualDistillation` 与 `VirtualDistillationConfig`。 +`cqlib.error_mitigation.virtual_distillation` 提供虚拟蒸馏的低层接口:把基础线路复制若干份,追加一个经 Hadamard 门制备的辅助比特,并在相邻副本之间施加由辅助比特控制的 SWAP(Hadamard-test 线路),再分别估计分子与分母,最后求比值得到缓解后的期望值。本页覆盖 `VirtualDistillation` 与 `VirtualDistillationConfig`。 ## 导入 @@ -50,7 +50,7 @@ from cqlib.error_mitigation.virtual_distillation import ( 参数: - `circuit` (`Circuit`):基础线路。构造时复制保存,不会修改传入的线路。 -- `copies` (`int`):拷贝份数,必须不小于 2,否则抛出 `ErrorMitigationError`。拷贝数决定缓解线路的宽度:copy-swap 线路的宽度为基础线路宽度的 `copies` 倍。 +- `copies` (`int`):拷贝份数,必须不小于 2,否则抛出 `ErrorMitigationError`。拷贝数决定缓解线路的宽度:copy-swap 线路的宽度为基础线路宽度的 `copies` 倍再加 1(多出的比特是 Hadamard 检验的辅助比特)。 ### 属性 @@ -59,7 +59,7 @@ from cqlib.error_mitigation.virtual_distillation import ( ### 方法 - `set_copies(copies)`:更新拷贝数。校验在赋值之前完成,校验失败时对象的拷贝数保持不变。 -- `build_copy_swap_circuit() -> Circuit`:构造 copy-swap 线路。基础线路先做分解,再逐份复制到各自比特区间,最后按位插入 SWAP。 +- `build_copy_swap_circuit() -> Circuit`:构造 copy-swap 线路。基础线路先做分解,再逐份复制到各自比特区间,最后在末尾辅助比特上施加 Hadamard 门,并在相邻副本之间按位施加由辅助比特控制的 SWAP。 - `run_denominator_circuit(shots, estimator) -> tuple[float, float]`:执行分母线路,返回回调给出的二元组。 - `run_numerator_circuit(hamiltonian, shots, estimator) -> tuple[float, float]`:执行分子线路,返回回调给出的二元组。 - `run_vd(hamiltonian, shots_numerator, shots_denominator, estimator) -> tuple[float, float]`:依次执行分子与分母并求比值,返回 `(缓解后的期望值, 方差)`。 @@ -78,9 +78,9 @@ from cqlib.error_mitigation.virtual_distillation import ( 1. 基础线路先做分解,保证复制的是一组已展开的操作。 2. 基础线路按 `copies` 份复制,第 `i` 份落在偏移 `i` 倍基础宽度的比特区间上。 -3. 对第 1 份与其余每一份,逐位插入 SWAP。SWAP 只在第 1 份与其他各份之间插入,其余份之间不直接相连。 +3. 在末尾追加一个辅助比特,经 `H` 门制备到 `|+⟩`;随后在相邻副本之间逐位插入 SWAP,全部由辅助比特控制(CSWAP)。这一受控 SWAP 梯实现 Hadamard 检验所需的副本轮换(derangement)。 -因此拷贝数为 2 时,基础线路每条操作出现 2 次,另加按位 SWAP;拷贝数增加时 SWAP 数量按份数线性增长,而不随拷贝数两两配对增长。 +因此拷贝数为 2 时,基础线路每条操作出现 2 次,另加辅助比特上的 1 个 `H` 与按位的受控 SWAP;拷贝数增加时受控 SWAP 数量按份数线性增长,而不随拷贝数两两配对增长。 ```python from cqlib.circuit import Circuit @@ -91,7 +91,7 @@ circuit.x(0) vd = VirtualDistillation(circuit, 2) copy_swap = vd.build_copy_swap_circuit() -print(copy_swap.width) # 2 +print(copy_swap.width) # 3 = copies * 基础宽度 + 1 ``` --- @@ -102,11 +102,13 @@ print(copy_swap.width) # 2 | 方法 | 回调收到的线路 | 回调收到的观测量 | 回调收到的采样次数 | | --- | --- | --- | --- | -| `run_denominator_circuit(shots, estimator)` | copy-swap 线路 | `None` | `shots` | -| `run_numerator_circuit(hamiltonian, shots, estimator)` | copy-swap 线路 | 按拷贝数扩展后的 `Hamiltonian` | `shots` | +| `run_denominator_circuit(shots, estimator)` | copy-swap 线路 | 辅助比特上为 `X`(其余为恒等)的 `Hamiltonian` | `shots` | +| `run_numerator_circuit(hamiltonian, shots, estimator)` | copy-swap 线路 | 扩展到全宽的 `Hamiltonian`(第 0 份副本上的 `O` ⊗ 辅助比特上的 `X`) | `shots` | | `run_vd(...)` | copy-swap 线路 | 先分子后分母,同上 | 分别为 `shots_numerator` 与 `shots_denominator` | -分子所用的观测量由传入的 `Hamiltonian` 扩展得到:原有 Pauli 项保留在各自比特上,更高位的比特补 `Z`,使观测量比特数与 copy-swap 线路宽度一致。扩展由类内部完成,调用方只需传入作用在基础线路上的观测量。 +分子与分母的观测量都是具体的 `Hamiltonian`,按内容区分:分子观测量在第 0 份副本的比特上有非恒等 Pauli,分母观测量只在辅助比特(最后一个比特)上非恒等。 + +分子所用的观测量由传入的 `Hamiltonian` 扩展得到:原有 Pauli 项保留在各自比特上(即第 0 份副本),其余副本补恒等 `I`,并在辅助比特上追加 `X`,使观测量比特数与 copy-swap 线路宽度一致。扩展由类内部完成,调用方只需传入作用在基础线路上的观测量。 `run_vd()` 依次完成两步:先按 `shots_numerator` 执行分子,再按 `shots_denominator` 执行分母,然后按下式合成结果: @@ -136,9 +138,16 @@ vd = VirtualDistillation(circuit, 2) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) # 分母:Tr(ρ^M) - return (1.5, 0.25) # 分子:Tr(O ρ^M) + # 分子与分母都携带观测量:分子在第 0 份副本的比特上有非恒等 Pauli, + # 分母只有辅助比特(最后一个比特)上的 X + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) # 分子:Tr(O ρ^M) + return (2.0, 1.0) # 分母:Tr(ρ^M) expectation, variance = vd.run_vd( diff --git a/docs/api/cn/python/6_error_mitigation/3_unified.md b/docs/api/cn/python/6_error_mitigation/3_unified.md index 74e91907..fec1ec5a 100644 --- a/docs/api/cn/python/6_error_mitigation/3_unified.md +++ b/docs/api/cn/python/6_error_mitigation/3_unified.md @@ -161,7 +161,7 @@ vd_args = RunArgs.virtual_distillation(shots_numerator=3, shots_denominator=2) 零噪声外推:`run()` 按配置的折叠等级构造缓解线路,对每条线路调用一次回调,观测量为传入的 `Hamiltonian`,采样次数取自 `RunArgs.zne(shots=...)`。回调返回的二元组只取第 1 个元素,方差被丢弃。`get_mitigated()` 对外推输入做拟合,结果的 `variance` 为 `None`。 -虚拟蒸馏:`run()` 先构造 copy-swap 线路,再在同一条线路上调用两次回调——先分子,后分母。分子传入按拷贝数扩展后的观测量与 `shots_numerator`,分母传入 `None` 与 `shots_denominator`。`get_mitigated()` 按 [虚拟蒸馏](2_virtual_distillation.md) 的合成公式求比值,结果的 `variance` 有值。 +虚拟蒸馏:`run()` 先构造 copy-swap 线路,再在同一条线路上调用两次回调——先分子,后分母。分子传入扩展到全宽的观测量(第 0 份副本上的原观测量 ⊗ 辅助比特上的 `X`)与 `shots_numerator`,分母传入仅辅助比特上带 `X` 的观测量与 `shots_denominator`。`get_mitigated()` 按 [虚拟蒸馏](2_virtual_distillation.md) 的合成公式求比值,结果的 `variance` 有值。 ### 示例 diff --git a/docs/api/cn/rust/0_circuit/4_operation_instruction.md b/docs/api/cn/rust/0_circuit/4_operation_instruction.md index 33a86171..7143049f 100644 --- a/docs/api/cn/rust/0_circuit/4_operation_instruction.md +++ b/docs/api/cn/rust/0_circuit/4_operation_instruction.md @@ -98,11 +98,25 @@ pub enum Instruction { | `is_delay()` | 是否为延迟指令。 | | `is_quantum_gate()` | 是否为酉量子门,即前四类之一。 | -### 3. 结构相等 +### 3. Payload 访问器 + +每个类别谓词都配有一个 payload 访问器,返回包裹的定义对象,调用方可以先用 `is_*()` 分派、再读取内容,无需手动模式匹配。变体不匹配时访问器一律返回 `None`。 + +| 方法 | 返回 | 说明 | +| --- | --- | --- | +| `standard_gate()` | `Option` | 当指令为标准门时,返回标准门定义。 | +| `mc_gate()` | `Option<&MCGate>` | 当指令为多控制门时,返回多控制门定义。 | +| `unitary_gate()` | `Option<&UnitaryGate>` | 当指令为自定义酉门时,返回酉门定义。 | +| `circuit_gate()` | `Option<&CircuitGate>` | 当指令为复合门时,返回复合门定义。 | +| `directive()` | `Option` | 当指令为非酉指令时,返回对应 `Directive`。 | +| `classical_data()` | `Option<&ClassicalDataOp>` | 当指令为经典数据操作时,返回经典数据操作。 | +| `classical_control()` | `Option<&ClassicalControlOp>` | 当指令为结构化控制流时,返回存储层控制流操作。 | + +### 4. 结构相等 `Instruction` 实现了 `PartialEq`。两个指令相等当且仅当变体与内部定义在结构上一致,比较过程不涉及量子比特绑定与参数取值。 -### 4. 常用方法 +### 5. 常用方法 | 方法 | 说明 | | --- | --- | @@ -113,7 +127,7 @@ pub enum Instruction { | `inverse(params)` | 尝试返回反指令及反参数;不可逆指令返回 `None`。 | | `control(num_new_ctrls)` | 尝试将当前指令提升为受控指令。 | -### 5. `From` 转换 +### 6. `From` 转换 `Instruction` 支持从多种底层类型转换而来,便于在构造 IR 或编译 pass 中快速创建指令。 @@ -277,7 +291,10 @@ pub enum ValueInstruction { | `is_standard()` / `is_mcgate()` / `is_unitary()` / `is_circuit_gate()` | 判断是否分别为标准门、多控制门、自定义酉门、复合门指令。 | | `is_directive()` / `is_classical_data()` / `is_delay()` | 判断是否分别为非酉指令、经典数据操作、延迟指令。 | | `standard_gate()` | 当指令为标准门时返回对应 `StandardGate`。 | +| `mc_gate()` / `unitary_gate()` / `circuit_gate()` | 当指令属于对应类别时,返回对应门定义的引用。 | | `directive()` | 当指令为非酉指令时返回对应 `Directive`。 | +| `classical_data()` | 当指令为经典数据操作时,返回对应 `ClassicalDataOp` 的引用。 | +| `classical_control()` | 当指令为构造层控制流时,返回对应 `ValueClassicalControlOp` 的引用。 | | `as_instruction()` | 读取内部 `Instruction` 引用。 | | `into_instruction()` | 消耗对象并取出内部 `Instruction`。 | @@ -419,4 +436,4 @@ op.label = Some("calibrated-rz".into()); circuit.validate()?; ``` -这样可以尽早发现 IR 构造问题,避免错误延迟到矩阵转换、设备映射或真实后端执行阶段。 \ No newline at end of file +这样可以尽早发现 IR 构造问题,避免错误延迟到矩阵转换、设备映射或真实后端执行阶段。 diff --git a/docs/api/cn/rust/1_ir/3_qasm3.md b/docs/api/cn/rust/1_ir/3_qasm3.md index 4e5d5779..ddda4dd8 100644 --- a/docs/api/cn/rust/1_ir/3_qasm3.md +++ b/docs/api/cn/rust/1_ir/3_qasm3.md @@ -99,6 +99,7 @@ use cqlib_core::ir::{qasm3_load, qasm3_loads, qasm3_dump, qasm3_dumps}; - 子程序与外部调用:`def` 子程序、`extern` - 硬件相关:硬件量子比特、`output` 声明,以及除角度与浮点以外的 `input` 声明 - 其它语句:`alias`、`pragma`、注解、旧式声明 +- 程序终止:`end`;任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 - 门修饰符:`negctrl`、`pow`;`ctrl` 与 `inv` 仅在目标门存在对应实现时可用 - 部分标准门:`ch`、`cp`、`cu`、`cswap` - 控制流:`while` 在实现中存在下降路径,但运行时条件的循环当前会被语义检查拒绝;`for` 只支持范围为常量的静态展开形式 diff --git a/docs/api/cn/rust/3_qis/1_statevector.md b/docs/api/cn/rust/3_qis/1_statevector.md index 33f14470..ed357327 100644 --- a/docs/api/cn/rust/3_qis/1_statevector.md +++ b/docs/api/cn/rust/3_qis/1_statevector.md @@ -32,7 +32,10 @@ pub struct Statevector { ### 构造与振幅访问 +`new` 在维度无法表示或状态内存分配失败时会 panic。需要处理错误时使用对应的 `try_*` 构造函数。支持零比特状态。 + - `fn new(num_qubits: usize) -> Self`:构造 `|0...0>` 态,首分量置 1,其余为 0。 +- `fn try_new(num_qubits: usize) -> Result`:构造基态;维度无法表示时返回 `QisError::InvalidParameterValue`,状态内存分配失败时返回 `QisError::UnsupportedOperation`。 - `fn from_state(num_qubits: usize, initial_state: Vec) -> Result`:用给定振幅构造,要求长度等于 `2^num_qubits` 且已经归一化。 - `fn data(&self) -> &[Complex64]`:按共享切片读取全部振幅。 - `fn data_mut(&mut self) -> &mut [Complex64]`:按可变切片读取全部振幅;改写可能破坏归一化。 diff --git a/docs/api/cn/rust/3_qis/2_density_matrix.md b/docs/api/cn/rust/3_qis/2_density_matrix.md index a28a52dc..456f1902 100644 --- a/docs/api/cn/rust/3_qis/2_density_matrix.md +++ b/docs/api/cn/rust/3_qis/2_density_matrix.md @@ -32,9 +32,14 @@ pub struct DensityMatrix { ### 构造与数据访问 +`new`、`zeros` 和 `maximally_mixed` 在维度无法表示或状态内存分配失败时会 panic。需要处理错误时使用对应的 `try_*` 构造函数。支持零比特状态。 + - `fn new(num_qubits: usize) -> Self`:构造纯态 `|0...0><0...0|`。 +- `fn try_new(num_qubits: usize) -> Result`:构造基态;维度无法表示时返回 `QisError::InvalidParameterValue`,状态内存分配失败时返回 `QisError::UnsupportedOperation`。 - `fn maximally_mixed(num_qubits: usize) -> Self`:构造最大混合态 `I / 2^N`,各计算基态等概率且无相干项。 +- `fn try_maximally_mixed(num_qubits: usize) -> Result`:对应的可失败构造,错误类型与 `try_new` 相同。 - `fn zeros(num_qubits: usize) -> Self`:构造全零矩阵;它不是合法物理态(迹为 0),用于作为量子信道等操作的累加起点。 +- `fn try_zeros(num_qubits: usize) -> Result`:对应的可失败构造,错误类型与 `try_new` 相同。 - `fn from_state(num_qubits: usize, initial_state: Vec) -> Result`:由纯态振幅做外积 `ρ = |ψ><ψ|` 构造。 - `fn from_density_matrix_state(num_qubits: usize, dm_state: Vec) -> Result`:直接由展平的 `2^N × 2^N` 矩阵构造,并校验 Hermitian 性、半正定性与单位迹。 - `fn data(&self) -> &[Complex64]`:按共享切片读取展平的矩阵元素。 diff --git a/docs/api/cn/rust/3_qis/3_density_matrix_noise.md b/docs/api/cn/rust/3_qis/3_density_matrix_noise.md index 05af1f38..bfab1bf8 100644 --- a/docs/api/cn/rust/3_qis/3_density_matrix_noise.md +++ b/docs/api/cn/rust/3_qis/3_density_matrix_noise.md @@ -35,7 +35,10 @@ pub struct DensityMatrixNoise { ### 构造与线路对接 +`new` 在维度无法表示或状态内存分配失败时会 panic。需要处理错误时使用对应的 `try_*` 构造函数。支持零比特状态。 + - `fn new(num_qubits: usize, noise_model: Option) -> Self`:按比特数与噪声模型构造,初始态为 `|0...0><0...0|`。 +- `fn try_new(num_qubits: usize, noise_model: Option) -> Result`:构造基态;维度无法表示时返回 `QisError::InvalidParameterValue`,状态内存分配失败时返回 `QisError::UnsupportedOperation`。 - `fn from_circuit(circuit: &Circuit, noise_model: Option) -> Result`:执行线路并返回模拟器;线路会先被分解为基础门,噪声在每个门之后施加。 - `fn apply_circuit(&mut self, circuit: &Circuit) -> Result<(), QisError>`:把线路原地作用到当前模拟器上,噪声按已配置的模型施加。 @@ -84,7 +87,7 @@ pub struct DensityMatrixNoise { 模拟器把「量子态的噪声」与「读出的噪声」分开表达:前者作用于密度矩阵本身,后者只改变报告出来的概率分布。 - `fn probabilities(&self) -> Vec`:返回密度矩阵对角元,即各计算基态的测量概率。包含已经施加的门噪声,不含读出噪声。 -- `fn probabilities_with_readout(&self, qubits: &[usize]) -> Result, QisError>`:在 `probabilities` 的基础上,对 `qubits` 中列出的比特施加读出噪声。 +- `fn probabilities_with_readout(&self, qubits: &[usize]) -> Result, QisError>`:`qubits` 为施加读出误差的存储位置;绑定线路后,按这些位置对应的线路比特 ID 查询噪声模型,未绑定时 ID 与位置相同。返回完整的 `2^num_qubits` 项概率数组,保持存储位序;空选择不施加读出误差。位置越界时返回 `QisError::IndexOutOfBounds`,即使未配置噪声模型。 - `fn probs(&self, measurement: &Measurement) -> Result, QisError>`:返回 `Measurement` 选定的边缘概率分布,不含读出噪声。 - `fn probs_with_readout(&self, measurement: &Measurement) -> Result, QisError>`:在 `probs` 的基础上,对 `measurement.qubits()` 施加读出噪声。 diff --git a/docs/api/cn/rust/3_qis/7_hamiltonian.md b/docs/api/cn/rust/3_qis/7_hamiltonian.md index a8a5cf38..ce86449d 100644 --- a/docs/api/cn/rust/3_qis/7_hamiltonian.md +++ b/docs/api/cn/rust/3_qis/7_hamiltonian.md @@ -1,11 +1,11 @@ # Hamiltonian 与 Observable -`cqlib_core::qis::hamiltonian` +`cqlib_core::qis::hamiltonian` `cqlib_core::qis::observable` -本页介绍由 Pauli 串与复系数构成的观测量 `Hamiltonian`,以及计算期望值的统一接口 `Observable` trait。 +本页介绍由 Pauli 串与复系数构成的算符 `Hamiltonian`,以及计算实数期望值的统一接口 `Observable` trait。 -`Hamiltonian` 是 $2^N \times 2^N$ 矩阵的稀疏表示,形式为 $H = \sum_k c_k P_k$,其中 $c_k$ 是复系数,$P_k$ 是 $N$ 比特 Pauli 串。同一个结构既用于物理解释中的哈密顿量,也用于任意需要求期望值的可观测量。 +`Hamiltonian` 是 $2^N \times 2^N$ 矩阵的稀疏表示,形式为 $H = \sum_k c_k P_k$,其中 $c_k$ 是复系数,$P_k$ 是 $N$ 比特 Pauli 串。该结构允许非厄米算符;实数期望值和酉演化入口会额外检查厄米性。 ## 导入 @@ -46,10 +46,59 @@ pub struct Hamiltonian { - `fn simplify(&mut self)`:化简项列表。该操作分两步:把每个 `PauliString` 的内部相位吸收进系数,使所有 Pauli 串归一到 `Phase::Plus`;再按 X、Z 分量向量分组,合并相同算子的系数。绝对值小于 $10^{-10}$ 的系数会被丢弃。 - `fn scale(&mut self, factor: Complex64)`:把所有项的系数乘以同一个复因子。 +### 安全 Pauli 和式代数 + +以下接口返回 `Result`,验证比特数、X/Z 位向量长度、有限系数及系数乘法/累加结果。返回的算符已吸收相位、按 Z 再 X 向量确定性排序并合并重复项,且只删除精确零;不采用 `simplify()` 的默认截断。 + +| 接口 | 语义 | +| --- | --- | +| `identity(num_qubits) -> Self` | 指定寄存器上的单位算符;零比特时为标量 1。 | +| `from_terms(num_qubits, terms) -> Result` | 从 `(PauliString, Complex64)` 的 `IntoIterator` 安全构造;空输入保留声明宽度。 | +| `try_add(&self, other: &Self)` / `try_sub(&self, other: &Self)` | 同宽度加减,返回 `Result`,不修改输入。 | +| `try_mul(&self, other: &Self) -> Result` | 矩阵乘积 $AB$,右操作数先作用;允许非厄米结果。 | +| `scaled(&self, factor: Complex64) -> Result` | 返回缩放结果;零算符也验证因子。 | +| `adjoint(&self) -> Result` | 相位归一化后共轭系数,得到 $A^\dagger$。 | +| `normalized(&self) -> Result` | 验证、吸收相位、合并同类项,仅删除精确零。 | +| `chop(&mut self, atol: f64) -> Result<(), QisError>` | 先归并,再删除复数模长 `≤ atol` 的项;失败时原值不变。 | +| `equiv(&self, other: &Self, atol: f64) -> Result` | 判断归一化后 $A-B$ 的每个系数模长是否 `≤ atol`。 | +| `is_hermitian(&self, atol: f64) -> Result` | 等价于与伴随的 `equiv`,不投影到实数。 | +| `tensor(&self, other: &Self) -> Result` | $A\otimes B$,B 占低比特,A 占高比特。 | +| `remap_qubits(&self, mapping: &[usize], target_width: usize) -> Result` | `mapping[source] = destination`;支持置换和嵌入,未使用位置补 I。 | + +所有容差必须有限且非负。`equiv` 使用逐项系数容差,不是矩阵算符范数界;宽度不同返回 `QubitMismatch`,不会隐式扩展寄存器。`is_hermitian` 的容差衡量 $A-A^\dagger$,归一化后等于虚部幅值的两倍,与 `FermionicOp` 一致。已有 `normalized_hermitian()` 使用独立消费者契约:允许虚部幅值不超过 `1e-10`,将其投影到实数,但保留任何非零实系数。 + +`remap_qubits` 要求映射长度等于源宽度,目标位置不重复且小于 `target_width`,包括零/单位算符。它不表示费米子模式置换或部分迹。零算符保留寄存器宽度,稀疏运算支持超过 64 个量子比特;乘法可展开成两侧项数的乘积,仍可能产生大量项。 + +若张量或嵌入结果需要构造 Pauli 项,宽度超过 BitVec 的可表示长度时返回 `UnsupportedOperation`,不会触发长度断言。零算符不需要位向量,可以保留更大的声明宽度。 + +```rust +use cqlib_core::qis::{Hamiltonian, QisError}; +use num_complex::Complex64; + +let x = Hamiltonian::from_pauli("X".parse()?); +let z = Hamiltonian::from_pauli("Z".parse()?); +let sum = x.try_add(&z)?; +assert!(sum.try_mul(&sum)?.equiv(&Hamiltonian::identity(1).scaled(2.0.into())?, 0.0)?); + +let xz = x.try_mul(&z)?; // XZ = -iY +let minus_i_y = Hamiltonian::from_terms(1, [("Y".parse()?, Complex64::new(0.0, -1.0))])?; +assert!(xz.equiv(&minus_i_y, 0.0)?); +assert!(!xz.is_hermitian(0.0)?); + +// [X,Z],以及 X ⊗ Z:最右字符对应比特 0。 +let commutator = xz.try_sub(&z.try_mul(&x)?)?; +assert!(commutator.equiv(&minus_i_y.scaled(2.0.into())?, 0.0)?); +assert!(x.tensor(&z)?.equiv(&Hamiltonian::from_pauli("XZ".parse()?), 0.0)?); +assert!(x.remap_qubits(&[2], 3)?.equiv(&Hamiltonian::from_pauli("XII".parse()?), 0.0)?); +# Ok::<(), QisError>(()) +``` + +旧 `Add`、`scale`、`simplify` 和构造器保留原契约;新调用优先使用安全接口。`PartialEq` 比较存储结构,项顺序、重复项或相位分布不同的等价算符可能不相等,应使用 `equiv`。 + ### 查询与转换 - `fn all_terms_commute(&self) -> bool`:判断所有 Pauli 项是否两两对易。为真时 $e^{-iHt}$ 可以按项分解为精确演化。 -- `fn to_matrix(&self) -> Result, QisError>`:返回 $2^N \times 2^N$ 稠密矩阵。任一项的比特数与 `num_qubits` 不一致时返回 `QisError::QubitMismatch`。空算量返回对应维度的零矩阵。 +- `fn to_matrix(&self) -> Result, QisError>`:验证并返回 $2^N \times 2^N$ 稠密矩阵。空算符返回对应维度的零矩阵,零比特输入返回 1×1 矩阵。分配前检查维度、元素数和字节数;大小溢出或内存预留失败返回 `UnsupportedOperation`。非法结构或非有限系数(包括矩阵元素累加溢出)返回相应错误。需要 $O(4^N)$ 内存,仅适用于小系统。 - `fn to_trotter_circuit(&self, time: f64, steps: usize, mode: TrotterMode) -> Result`:见 [Trotter 演化](8_evolution.md)。 - `fn to_evolution_circuit(&self, time: f64, steps: usize, mode: TrotterMode) -> Result`:见 [Trotter 演化](8_evolution.md)。 @@ -175,6 +224,8 @@ pub trait Observable { - `fn variance_statevector(&self, sv: &Statevector) -> Result`:计算纯态方差 $\text{Var}(O) = \langle O^2 \rangle - \langle O \rangle^2$。trait 中的默认实现返回 `QisError::UnsupportedOperation`,支持方差计算的观测量需要覆写该方法。 +实数期望值和方差接口在吸收相位、合并重复项后检查厄米性,不删除非零小系数。原始或合并后系数非有限时返回 `QisError::InvalidParameterValue`,非厄米算符返回 `QisError::NotHermitian`。 + ### 实现者 | 类型 | 说明 | diff --git a/docs/api/cn/rust/3_qis/8_evolution.md b/docs/api/cn/rust/3_qis/8_evolution.md index 73e420db..2870f773 100644 --- a/docs/api/cn/rust/3_qis/8_evolution.md +++ b/docs/api/cn/rust/3_qis/8_evolution.md @@ -193,7 +193,7 @@ assert!(circuit.pauli_evolution(&pauli, 1.0, &qubits).is_err()); - `steps` (`usize`):Trotter 步数 $n$,必须大于 0。 - `mode` (`TrotterMode`):分解模式。 -两者都先复制一份 Hamilton 量并化简,再检查系数的虚部:虚部绝对值超过 $10^{-10}$ 时返回 `QisError::NotHermitian`,因为只有 Hermitian 算符才能生成酉演化。 +两者都先复制一份 Hamilton 量,吸收 Pauli 相位并合并重复项,保留非零小系数,再检查系数的虚部:虚部绝对值超过 $10^{-10}$ 时返回 `QisError::NotHermitian`,因为只有 Hermitian 算符才能生成酉演化。 ### `fn to_trotter_circuit(&self, time: f64, steps: usize, mode: TrotterMode) -> Result` diff --git a/docs/api/cn/rust/3_qis/9_metrics_entropy.md b/docs/api/cn/rust/3_qis/9_metrics_entropy.md index 26598d7c..7a41b162 100644 --- a/docs/api/cn/rust/3_qis/9_metrics_entropy.md +++ b/docs/api/cn/rust/3_qis/9_metrics_entropy.md @@ -1,6 +1,6 @@ # 度量与熵 -`cqlib_core::qis::metrics` +`cqlib_core::qis::metrics` `cqlib_core::qis::entropy` 本页介绍量子态之间的度量与信息量函数。`metrics` 集合纯度、保真度、迹距离、冯·诺依曼熵与偏转置相关的量;`entropy` 集合线性熵、Rényi 熵,以及针对纠缠的度量。两模块的函数都以态矢量或密度矩阵为输入,返回 `Result`(`density_matrix_to_faer` 除外)。 @@ -143,6 +143,8 @@ assert!((trace_distance_mixed(&dm0, &dm1).unwrap() - 1.0).abs() < 1e-10); ### `renyi_entropy(dm: &DensityMatrix, alpha: f64) -> Result` +阶数必须为正且不能为 NaN。`alpha = 1` 返回冯·诺依曼熵,正无穷返回最小熵;接近 1 时使用稳定计算。非对角矩阵中不超过 `矩阵维度 × f64::EPSILON × 最大特征值` 的特征值视为数值零;对角矩阵保留全部正特征值。 + Rényi 熵 $S_\alpha(\rho) = \frac{1}{1-\alpha}\log_2\left(\sum_i \lambda_i^\alpha\right)$,$\lambda_i$ 为密度矩阵的特征值。$\alpha$ 不大于 0 时返回 `QisError::InvalidParameterValue`;$\alpha$ 与 1 的差小于 `f64::EPSILON` 时改用冯·诺依曼熵,避免除零。结果截断为非负值。 示例: @@ -283,7 +285,7 @@ assert!(partial_transpose(&dm, &[2]).is_err()); | 错误 | 触发场景 | | --- | --- | | `QisError::QubitMismatch` | 参与运算的两个态比特数不一致。 | -| `QisError::InvalidParameterValue` | `renyi_entropy()` 的 `alpha` 不大于 0。 | +| `QisError::InvalidParameterValue` | `renyi_entropy()` 的 `alpha` 为 NaN 或不大于 0。 | | `QisError::InvalidSubsystem` | `entanglement_entropy_pure()` 的子系统为空、包含全部比特或存在重复下标。 | | `QisError::IndexOutOfBounds` | `partial_transpose()` 的目标下标越界,或 `entanglement_entropy_pure()` 的子系统下标越界。 | | `QisError::UnsupportedDimension` | `concurrence()` 与 `entanglement_of_formation()` 的输入不是双比特。 | diff --git a/docs/api/cn/rust/4_compile/6_decompose_resynthesis.md b/docs/api/cn/rust/4_compile/6_decompose_resynthesis.md index bda086fe..144e80a4 100644 --- a/docs/api/cn/rust/4_compile/6_decompose_resynthesis.md +++ b/docs/api/cn/rust/4_compile/6_decompose_resynthesis.md @@ -47,12 +47,15 @@ use cqlib_core::compile::transform::DeviceLowerer; - `decompose_unitaries_with_rule_stats(circuit: &Circuit, config: UnitaryDecomposeConfig) -> Result<(TransformOutcome, DecompositionRuleStats), CompilerError>` - `DecomposeUnitaries`:`Transformer` 适配器,配置在构造时绑定,`DecomposeUnitaries::new(config)` 构造,实现 `Default`。 +对于三比特及以上的矩阵,该 pass 使用 Block-ZXZ 分解,并在路由与目标门集转换之前输出标准门序列。门的第一个比特参数对应矩阵最高有效位。规则缓存会连同操作序列一起保存全局相位;当规则应用于控制流体内部时,条件体将获得其对应的相位。 + ### UnitaryDecomposeConfig ```rust pub struct UnitaryDecomposeConfig { pub two_qubit_target: TwoQubitSynthesisTarget, pub recurse_control_flow: bool, + pub block_zxz_options: BlockZxzDecomposeOptions, } ``` @@ -60,8 +63,9 @@ pub struct UnitaryDecomposeConfig { - `two_qubit_target`:精确双比特数值合成使用的目标能力,由 `TwoQubitSynthesisTarget::from_instructions(target_basis: Option<&[Instruction]>)` 构造;`None` 表示无目标约束,启用中立的 Pauli 旋转回退。 - `recurse_control_flow`:是否递归进入控制流块。 +- `block_zxz_options`:应用于三比特及以上 Block-ZXZ 合成的优化开关(`BlockZxzDecomposeOptions::default()` 默认启用 A.1 和 A.2,并自动处理块对角输入)。 -实现 `Default`,等价于无目标约束且递归进入控制流块。 +实现 `Default`,等价于无目标约束、递归进入控制流块,并使用默认 Block-ZXZ 选项。 ### DecompositionRuleStats @@ -77,6 +81,12 @@ pass 内规则缓存统计:命中、未命中与写入次数。 --- +## Block-ZXZ 合成 + +`cqlib_core::compile::transform::decompose` 模块重新导出了 `decompose_block_zxz(matrix, atol)` 和 `decompose_block_zxz_with_options(matrix, atol, &options)`。两者均接收 `&Array2` 并返回 `Result`。输入需为维度 `2^n`(`n >= 1`)的有限方阵酉矩阵。局部比特 0 为矩阵最低有效位。返回的线路矩阵包含输入矩阵的全局相位。有限非负绝对容差 `atol` 用于校验输入酉性(`||M†M - I||_max <= atol`)并控制解复用器与双比特叶子的重构误差;通过输入校验的近酉矩阵会在需要时先投影到所有酉不变范数下最近的精确酉矩阵 `U_proj`,再以 `atol` 为容差重构 `U_proj`。 + +`BlockZxzDecomposeOptions::default()` 默认启用 `opt_a1`(吸收边界 CX 门)和 `opt_a2`(在双比特叶子之间转移对角余项)。当 `opt_a2` 启用时,`opt_a2_force` 允许对块对角输入也执行 A.2 优化。对于三比特及以上输入,精确块对角矩阵仅使用单个解复用器;若上下两半相等,最高位比特保持空闲。若某个双比特 KAK 叶子无法达到请求精度,合成器会针对原始 4×4 矩阵额外检查一层 Block-ZXZ 回退;数值回退可能会输出显式对角门与额外门。 + ## 数值酉门合成 `cqlib_core::compile::transform::decompose::unitary` 提供矩阵到门序列的直接合成,不经过线路遍历。 diff --git a/docs/api/cn/rust/5_visualization/3_state_plots.md b/docs/api/cn/rust/5_visualization/3_state_plots.md index 1f35cca1..533209bf 100644 --- a/docs/api/cn/rust/5_visualization/3_state_plots.md +++ b/docs/api/cn/rust/5_visualization/3_state_plots.md @@ -118,6 +118,8 @@ assert!(svg.contains("Re[rho]")); 把泡利基期望值绘制为柱状图。标签为 `I`、`X`、`Y`、`Z` 的张量积,共 `4^n` 条,其中 `n` 为量子比特数。非负柱与负值柱使用不同颜色。 +默认标签遵循 `PauliString`:最高位在左,qubit 0 在最右侧。例如,两比特态的 `IX` 表示 qubit 0 上的 X。启用 `reverse_bits` 仅反转每个标签中的字符顺序,对应的期望值不变。 + 参数: - `state` (`&S`,`S: StateVisualizationSource + ?Sized`):输入态。 diff --git a/docs/api/cn/rust/6_error_mitigation/0_overview.md b/docs/api/cn/rust/6_error_mitigation/0_overview.md index 57238c44..50dffb35 100644 --- a/docs/api/cn/rust/6_error_mitigation/0_overview.md +++ b/docs/api/cn/rust/6_error_mitigation/0_overview.md @@ -24,7 +24,7 @@ pub type Estimator<'a> = dyn Fn(&Circuit, Option<&Hamiltonian>, Option) -> (f64, f64) + 'a; ``` -参数依次为待执行线路、待估计的可观测量与 shot 数,返回 `(期望值, 方差)`。分母线路不携带可观测量,第二个参数为 `None`;`ZNEMitigation::run_em_sequence` 不指定 shot 数,第三个参数为 `None`。公开方法统一以 `&Estimator<'_>` 接收它,即 trait 对象引用 `&dyn Fn(&Circuit, Option<&Hamiltonian>, Option) -> (f64, f64)`,闭包与函数项都可以直接取引用传入。返回值中的方差只有虚拟蒸馏会使用,零噪声外推只取期望值。 +参数依次为待执行线路、待估计的可观测量与 shot 数,返回 `(期望值, 方差)`。虚拟蒸馏的分子与分母调用都会传入具体可观测量——分母可观测量是 copy-swap 线路辅助比特上的 `X`;`ZNEMitigation::run_em_sequence` 不指定 shot 数,第三个参数为 `None`。公开方法统一以 `&Estimator<'_>` 接收它,即 trait 对象引用 `&dyn Fn(&Circuit, Option<&Hamiltonian>, Option) -> (f64, f64)`,闭包与函数项都可以直接取引用传入。返回值中的方差只有虚拟蒸馏会使用,零噪声外推只取期望值。 ### 缓解流水线状态 @@ -100,8 +100,8 @@ assert_eq!(mitigated.expectation, 0.5); | **门折叠** | 把线路改写为 `U -> U (U† U)^level` 的构造方式;只对指定门折叠时称为选择性折叠。 | | **虚拟蒸馏** | 通过副本与 copy-swap 线路估计 `Tr(O ρ^M) / Tr(ρ^M)` 的方法,`M` 为副本数。 | | **副本(copy)** | 虚拟蒸馏中并行准备的基底线路份数,最少为 2。 | -| **copy-swap 线路** | 把多份基底线路并排放在互不重叠的比特区间、并在首份与其他每份之间插入逐比特 SWAP 的线路,宽度等于副本数乘以基底线路宽度。 | -| **分子线路 / 分母线路** | 虚拟蒸馏的两条统计线路。分子线路携带扩展后的可观测量;分母线路不携带可观测量,估计器收到 `None`。 | +| **copy-swap 线路** | 把多份基底线路并排放在互不重叠的比特区间、在末尾追加一个经 Hadamard 门制备到 `|+⟩` 的辅助比特、并在相邻副本之间施加由辅助比特控制的逐比特 SWAP 梯的线路,宽度等于副本数乘以基底线路宽度再加 1。 | +| **分子线路 / 分母线路** | 虚拟蒸馏的两条统计线路。分子线路携带扩展后的可观测量(第 0 份副本上的原可观测量与辅助比特上的 `X`);分母线路携带辅助比特上的 `X`,其余比特为恒等。 | | **缓解流水线** | `ErrorMitigation` 表示的顺序式流程:`new` 创建、`run` 收集原始数据、`get_mitigated` 做方法相关的后处理。 | --- @@ -159,7 +159,8 @@ let mut mitigation = ErrorMitigation::new( ) .unwrap(); -// 分子线路带可观测量,分母线路不带 +// 分子与分母都携带可观测量:分子在第 0 份副本的比特上有非恒等 Pauli, +// 分母只有辅助比特上的 X mitigation .run( &hamiltonian, @@ -168,7 +169,12 @@ mitigation shots_denominator: 2, }, &|_circuit, hamiltonian_arg, shots| { - if hamiltonian_arg.is_some() { + let observable = hamiltonian_arg.unwrap(); + let is_numerator = observable + .terms + .iter() + .any(|(term, _)| term.get_pauli(0) != Pauli::I); + if is_numerator { assert_eq!(shots, Some(3)); (1.5, 0.25) } else { @@ -232,13 +238,18 @@ let hamiltonian = Hamiltonian::from_list(vec![(pauli, Complex64::new(1.0, 0.0))] let vd = VirtualDistillation::new(Circuit::new(1), 2).unwrap(); -// 两份基底线路加一对逐比特 SWAP +// 两份基底线路加 1 个辅助比特:辅助比特上的 H 与一次受控 SWAP let copy_swap = vd.build_copy_swap_circuit().unwrap(); -assert_eq!(copy_swap.width(), 2); +assert_eq!(copy_swap.width(), 3); let (mu_vd, var_vd) = vd .run_vd(&hamiltonian, 3, 2, &|_circuit, hamiltonian_arg, shots| { - if hamiltonian_arg.is_some() { + let observable = hamiltonian_arg.unwrap(); + let is_numerator = observable + .terms + .iter() + .any(|(term, _)| term.get_pauli(0) != Pauli::I); + if is_numerator { assert_eq!(shots, Some(3)); (1.5, 0.25) } else { diff --git a/docs/api/cn/rust/6_error_mitigation/2_virtual_distillation.md b/docs/api/cn/rust/6_error_mitigation/2_virtual_distillation.md index 13f1ecfe..d5c6fc29 100644 --- a/docs/api/cn/rust/6_error_mitigation/2_virtual_distillation.md +++ b/docs/api/cn/rust/6_error_mitigation/2_virtual_distillation.md @@ -32,7 +32,7 @@ pub struct VirtualDistillation { - `fn new(circuit: Circuit, copies: usize) -> Result`:创建入口,取得线路所有权。模板线路只能通过 `new` 传入,没有对应的读接口。 - `fn set_copies(&mut self, copies: usize) -> Result<(), ErrorMitigationError>`:更新副本数。更新失败时保持原值不变。 - `fn build_copy_swap_circuit(&self) -> Result`:由基底线路构造 copy-swap 线路。 -- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), CircuitError>`:跑分母线路,返回 `(均值, 方差)`。 +- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`:跑分母线路,返回 `(均值, 方差)`。 - `fn run_numerator_circuit(&self, hamiltonian: &Hamiltonian, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`:跑分子线路,返回 `(均值, 方差)`。 - `fn run_vd(&self, hamiltonian: &Hamiltonian, shots_numerator: usize, shots_denominator: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`:跑完整流程,返回缓解后的 `(期望值, 方差)`。 @@ -55,10 +55,10 @@ pub struct VirtualDistillation { ### `build_copy_swap_circuit(&self) -> Result` -构造 copy-swap 线路,包含三个部分:先对基底线路做门分解,再把基底线路并排准备 `copies` 份——第 `i` 份整体平移到从 `i × 基底宽度` 开始的比特区间,各份之间互不重叠——最后在首份与其他每一份之间逐比特插入 `SWAP`。 +构造 copy-swap 线路——即虚拟蒸馏协议的 Hadamard-test 线路——包含三个部分:先对基底线路做门分解,再把基底线路并排准备 `copies` 份——第 `i` 份整体平移到从 `i × 基底宽度` 开始的比特区间,各份之间互不重叠——最后在末尾的辅助比特(最后一个比特)上施加 `H` 门制备到 `|+⟩`,并在相邻副本之间施加由辅助比特控制的 `SWAP` 梯(CSWAP),实现各副本的轮换(derangement)。 -- 线路宽度为 `copies × 基底宽度`,其中基底宽度取分解后线路的宽度。 -- 操作数为 `copies` 份基底操作加上 `(copies - 1) × 基底宽度` 个 `SWAP`。 +- 线路宽度为 `copies × 基底宽度 + 1`,其中基底宽度取分解后线路的宽度,最后一个比特是辅助比特。 +- 操作数为 `copies` 份基底操作加上 1 个 `H` 与 `(copies - 1) × 基底宽度` 个受控 `SWAP`。 返回: @@ -70,8 +70,8 @@ pub struct VirtualDistillation { ### 分子与分母 -- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), CircuitError>`:在 copy-swap 线路上估计分母 `Tr(ρ^M)`。估计器收到的可观测量参数为 `None`,shot 数为 `Some(shots)`;回调形态见 [概览](0_overview.md)。 -- `fn run_numerator_circuit(&self, hamiltonian: &Hamiltonian, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`:在 copy-swap 线路上估计分子 `Tr(O ρ^M)`。可观测量会在模块内部先扩展到 copy-swap 线路的宽度:原有 Pauli 项保持原比特索引与相位、系数不变,新增的高索引比特上补 `Z`;扩展结果经估计器的可观测量参数传入,shot 数为 `Some(shots)`。 +- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`:在 copy-swap 线路上估计分母 `Tr(ρ^M)`。估计器收到的可观测量参数为 `Some(分母观测量)`——辅助比特(最后一个比特)上的 `X`,其余比特为恒等——shot 数为 `Some(shots)`;回调形态见 [概览](0_overview.md)。 +- `fn run_numerator_circuit(&self, hamiltonian: &Hamiltonian, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`:在 copy-swap 线路上估计分子 `Tr(O ρ^M)`。可观测量会在模块内部先扩展到 copy-swap 线路的宽度:原有 Pauli 项保持原比特索引(即作用在第 0 份副本上)与相位、系数不变,其余副本补恒等 `I`,并在辅助比特(最后一个比特)上追加 `X`;扩展结果经估计器的可观测量参数传入,shot 数为 `Some(shots)`。 - `fn run_vd(&self, hamiltonian: &Hamiltonian, shots_numerator: usize, shots_denominator: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`:先校验哈密顿量的比特数等于基底线路宽度,再依次执行分子线路与分母线路,最后组合成缓解结果。分子与分母使用各自的 shot 数。 `run_vd` 的异常情况: @@ -94,11 +94,12 @@ let q0 = Qubit::new(0); let mut circuit = Circuit::new(1); circuit.x(q0).unwrap(); -// 两份单比特副本:X 作用于比特 0、X 作用于比特 1,再加一对逐比特 SWAP +// 两份单比特副本加 1 个辅助比特:X 作用于比特 0、X 作用于比特 1, +// 辅助比特(比特 2)上的 H,以及一次由辅助比特控制的 SWAP let vd = VirtualDistillation::new(circuit, 2).unwrap(); let copy_swap = vd.build_copy_swap_circuit().unwrap(); -assert_eq!(copy_swap.width(), 2); -assert_eq!(copy_swap.operations().len(), 3); +assert_eq!(copy_swap.width(), 3); +assert_eq!(copy_swap.operations().len(), 4); ``` ```rust @@ -127,11 +128,17 @@ let mut pauli = PauliString::new(1); pauli.set_pauli(0, Pauli::Z); let hamiltonian = Hamiltonian::from_list(vec![(pauli, Complex64::new(1.0, 0.0))]).unwrap(); -// 分子线路带可观测量,分母线路不带;两者使用各自的 shot 数 +// 分子与分母都携带可观测量,按内容区分:分子在第 0 份副本的比特上有 +// 非恒等 Pauli,分母只有辅助比特上的 X;两者使用各自的 shot 数 let vd = VirtualDistillation::new(Circuit::new(1), 2).unwrap(); let (mu_vd, var_vd) = vd .run_vd(&hamiltonian, 3, 2, &|_circuit, hamiltonian_arg, shots| { - if hamiltonian_arg.is_some() { + let observable = hamiltonian_arg.unwrap(); + let is_numerator = observable + .terms + .iter() + .any(|(term, _)| term.get_pauli(0) != Pauli::I); + if is_numerator { assert_eq!(shots, Some(3)); (1.5, 0.25) } else { @@ -175,6 +182,6 @@ pub struct VirtualDistillationConfig { | `ErrorMitigationError::HamiltonianQubitCountMismatch` | `run_vd` 收到的哈密顿量比特数与基底线路宽度不一致。 | | `ErrorMitigationError::ZeroDenominatorMean` | 分母线路的均值为零。 | | `ErrorMitigationError::Circuit` | 携带 `CircuitError::QubitCountMismatch`,表示扩展后的可观测量宽度与 copy-swap 线路宽度不一致。 | -| `CircuitError` | `build_copy_swap_circuit` 与 `run_denominator_circuit` 直接返回的线路错误。 | +| `CircuitError` | `build_copy_swap_circuit` 直接返回的线路错误;`run_denominator_circuit` 将其包装为 `ErrorMitigationError::Circuit`。 | 错误类型的完整定义见 [统一流水线](3_unified.md)。 diff --git a/docs/api/cn/rust/6_error_mitigation/3_unified.md b/docs/api/cn/rust/6_error_mitigation/3_unified.md index 92977a3b..e16cd87c 100644 --- a/docs/api/cn/rust/6_error_mitigation/3_unified.md +++ b/docs/api/cn/rust/6_error_mitigation/3_unified.md @@ -77,7 +77,7 @@ pub struct ErrorMitigation { 执行细节按方法区分: - 零噪声外推:按配置的折叠等级构造折叠线路,逐条调用估计器,可观测量参数为 `Some(hamiltonian)`,shot 数为 `RunArgs::Zne::shots`;只取返回值中的期望值。折叠线路、期望值、噪声因子与执行参数一并留存。 -- 虚拟蒸馏:构造 copy-swap 线路并把可观测量扩展到该线路宽度,分子线路的估计器收到 `Some(扩展后的可观测量)` 与 `Some(shots_numerator)`,分母线路收到 `None` 与 `Some(shots_denominator)`;分子与分母的均值、方差一并留存。 +- 虚拟蒸馏:构造 copy-swap 线路并把可观测量扩展到该线路宽度,分子线路的估计器收到 `Some(扩展后的可观测量)`——第 0 份副本上的原可观测量与辅助比特上的 `X`——与 `Some(shots_numerator)`,分母线路收到 `Some(分母可观测量)`——辅助比特上的 `X`,其余比特为恒等——与 `Some(shots_denominator)`;分子与分母的均值、方差一并留存。 返回: diff --git a/docs/api/en/c/1_ir/3_qasm3.md b/docs/api/en/c/1_ir/3_qasm3.md index 26bd2a29..ddfcb2b2 100644 --- a/docs/api/en/c/1_ir/3_qasm3.md +++ b/docs/api/en/c/1_ir/3_qasm3.md @@ -84,6 +84,7 @@ The following features produce an explicit error rather than partial degradation - Subprograms and externals: `def` subprograms, `extern` - Hardware-related: hardware qubits, `output` declarations, and `input` declarations other than angle and float - Other statements: `alias`, `pragma`, annotations, legacy declarations +- Program termination: `end` is explicitly rejected in every scope, including unreachable branches and zero-iteration loops - Gate modifiers: `negctrl`, `pow`; `ctrl` and `inv` only work when the target gate has a matching implementation - Some standard gates: `ch`, `cp`, `cu`, `cswap` - Control flow: `while` over a runtime condition is rejected by semantic checks; `for` only supports static expansion of constant ranges diff --git a/docs/api/en/c/3_qis/0_overview.md b/docs/api/en/c/3_qis/0_overview.md index cc94ee7b..b6f69def 100644 --- a/docs/api/en/c/3_qis/0_overview.md +++ b/docs/api/en/c/3_qis/0_overview.md @@ -84,3 +84,5 @@ int main(void) { ``` For constructing and populating the `CNoiseModel` handle, see [NoiseModel](../2_device/4_noise.md). + +New [fermionic algebra and Jordan–Wigner](10_fermion.md) and [checked Hamiltonian algebra](7_hamiltonian.md#checked-sparse-pauli-algebra) use error codes plus output pointers: constructors deliver handles through outputs and predicates write 0/1 bytes. Existing QIS functions retain their original conventions. diff --git a/docs/api/en/c/3_qis/10_fermion.md b/docs/api/en/c/3_qis/10_fermion.md new file mode 100644 index 00000000..44822fab --- /dev/null +++ b/docs/api/en/c/3_qis/10_fermion.md @@ -0,0 +1,179 @@ +# Fermionic algebra and Jordan–Wigner (C) + +`CFermionicOp` is a sparse complex sum of ordered ladder products. Modes are zero-based; in `A B`, B acts first. Identical ordered products merge and only exact zeros disappear. No implicit normal ordering or numerical pruning occurs. Zero and identity retain the declared mode count, including zero modes. + +## ABI and data + +New `int32_t` functions return 0 on success. Objects use `**out` and scalar queries use output pointers; errors leave outputs and mutable inputs unchanged. Results are independently owned and freed with `fermionic_op_free`; inputs are borrowed and copied. Pass an empty output slot and valid, aligned, live storage. Output slots must not overlap one another or handle internals, and a handle must not be read concurrently with mutation. Empty arrays allow NULL; nonempty arrays require sufficient storage. + +Errors: -1 required NULL pointer; -2 mode/term index out of bounds; -8 invalid tag, mode-count mismatch, nonfinite coefficient/arithmetic overflow, invalid tolerance, insufficient capacity or unrepresentable array length; -7 unsupported Pauli representation width. Predicates write 0/1 to `uint8_t *out`; their successful return code is always 0. + +```c +typedef struct CFermionicOp CFermionicOp; +#define FERMIONIC_CREATE 0 +#define FERMIONIC_ANNIHILATE 1 +typedef struct CFermionicLadder { + size_t mode; + uint8_t kind; +} CFermionicLadder; +typedef struct CFermionicTerm { + const CFermionicLadder *ladders; + size_t len; + Complex64 coefficient; +} CFermionicTerm; +``` + +## Construction + +```c +int32_t fermionic_op_new(size_t num_modes, CFermionicOp **out); + +int32_t fermionic_op_identity(size_t num_modes, CFermionicOp **out); + +int32_t fermionic_op_from_term(size_t num_modes, + const CFermionicLadder *term, + size_t len, + Complex64 coefficient, + CFermionicOp **out); + +int32_t fermionic_op_from_terms(size_t num_modes, + const CFermionicTerm *terms, + size_t len, + CFermionicOp **out); + +int32_t fermionic_op_creation(size_t num_modes, size_t mode, CFermionicOp **out); + +int32_t fermionic_op_annihilation(size_t num_modes, size_t mode, CFermionicOp **out); + +int32_t fermionic_op_number(size_t num_modes, size_t mode, CFermionicOp **out); + +int32_t fermionic_op_total_number(size_t num_modes, CFermionicOp **out); + +int32_t fermionic_op_excitation_generator(size_t num_modes, + const size_t *sources, + size_t sources_len, + const size_t *targets, + size_t targets_len, + CFermionicOp **out); +``` + +- `new` creates zero and `identity` creates one. An empty `from_term` product is identity; an empty `from_terms` sum is zero. Batch descriptors and nested ladder arrays are borrowed only during the call. Even zero-weight products validate tags and modes. +- `creation/annihilation/number` construct a†, a, and a†a; `total_number` sums the number operator over all modes. +- Excitation generates G=i(T−T†), with target creators in input order and source annihilators in reverse order. Lists must be nonempty, equally long, individually unique and disjoint. An odd permutation changes the sign. No sorting, factorial or spin-orbital convention is imposed. + +## Lifetime and queries + +```c +void fermionic_op_free(CFermionicOp *ptr); + +int32_t fermionic_op_copy(const CFermionicOp *ptr, CFermionicOp **out); + +int32_t fermionic_op_num_modes(const CFermionicOp *ptr, size_t *out); + +int32_t fermionic_op_num_terms(const CFermionicOp *ptr, size_t *out); + +int32_t fermionic_op_is_zero(const CFermionicOp *ptr, uint8_t *out); + +int32_t fermionic_op_equals(const CFermionicOp *left, + const CFermionicOp *right, + uint8_t *out); + +int32_t fermionic_op_term_len(const CFermionicOp *ptr, size_t index, size_t *out); + +int32_t fermionic_op_get_term(const CFermionicOp *ptr, + size_t index, + CFermionicLadder *buffer, + size_t capacity, + Complex64 *out_coefficient); +``` + +`free(NULL)` is valid; `copy` is independent. `is_zero` tests empty storage and `equals` compares stored structure and mode count (different mode counts return false). Use `equiv` for algebraic equality. + +Call `term_len`, allocate a buffer, then call `get_term`. Capacity may exceed the required length; trailing elements stay untouched. Empty products allow NULL buffer. Terms follow core deterministic structural order; requery lengths and indices after mutation. Output arrays are copies and contain no library-owned pointers to release. + +## Algebra + +```c +int32_t fermionic_op_add_term(CFermionicOp *ptr, + const CFermionicLadder *term, + size_t len, + Complex64 coefficient); + +int32_t fermionic_op_add(const CFermionicOp *left, + const CFermionicOp *right, + CFermionicOp **out); + +int32_t fermionic_op_sub(const CFermionicOp *left, + const CFermionicOp *right, + CFermionicOp **out); + +int32_t fermionic_op_mul(const CFermionicOp *left, + const CFermionicOp *right, + CFermionicOp **out); + +int32_t fermionic_op_scaled(const CFermionicOp *ptr, + Complex64 factor, + CFermionicOp **out); + +int32_t fermionic_op_adjoint(const CFermionicOp *ptr, CFermionicOp **out); + +int32_t fermionic_op_normal_order(const CFermionicOp *ptr, CFermionicOp **out); + +int32_t fermionic_op_chop(CFermionicOp *ptr, double atol); + +int32_t fermionic_op_equiv(const CFermionicOp *left, + const CFermionicOp *right, + double atol, + uint8_t *out); + +int32_t fermionic_op_is_hermitian(const CFermionicOp *ptr, double atol, uint8_t *out); +``` + +`add_term/chop` mutate in place; other object operations return copies. `mul` does not normal order. `adjoint` conjugates coefficients, reverses products and exchanges ladder kinds. `normal_order` places creators before annihilators with ascending modes within each group, including anticommutation contractions. + +`chop` removes coefficients with magnitude <= atol. `equiv` normal-orders the difference and compares coefficients, requiring equal mode counts; `is_hermitian` compares with the adjoint. atol must be finite and nonnegative; explicitly pass 0 for exact comparison. This is a coefficient tolerance, not a matrix operator-norm bound. + +## Jordan–Wigner + +```c +int32_t jordan_wigner_map_operator(const CFermionicOp *ptr, CHamiltonian **out); + +int32_t jordan_wigner_num_qubits(size_t num_modes, size_t *out); + +int32_t jordan_wigner_map_occupation(const uint8_t *occupation, + size_t len, + uint8_t *out_bits, + size_t capacity); +``` + +Mapping is stateless and needs no mapper handle. Mode p maps to qubit p with Z on lower modes: creation = Z-chain (X−iY)/2 and annihilation = Z-chain (X+iY)/2. Qubit 0 is the least significant bit and rightmost displayed Pauli character. + +`map_operator` returns an independent `CHamiltonian`, freed with `hamiltonian_free`. Non-Hermitian inputs are valid; downstream expectation and evolution functions check Hermiticity. Mapping builds no dense matrix, but a product of k ladders may expand to 2^k terms before merging. + +`map_occupation` accepts only 0/1 bytes. Input length defines the mode count; output bits[p] addresses qubit p. Capacity must be at least len; input and output may overlap. Empty input is zero-mode vacuum. + +## Example + +```c +#include "cqlib_c.h" + +int main(void) { + const size_t sources[] = {0}, targets[] = {1}; + CFermionicOp *g = NULL; + CHamiltonian *h = NULL; + if (fermionic_op_excitation_generator(2, sources, 1, targets, 1, &g) != 0) { + return 1; + } + if (jordan_wigner_map_operator(g, &h) != 0) { + fermionic_op_free(g); + return 1; + } + CCircuit *u = hamiltonian_to_evolution_circuit( + h, 0.37, 1, TROTTER_MODE_SECOND_ORDER); + const int result = u == NULL ? 1 : 0; + circuit_free(u); + hamiltonian_free(h); + fermionic_op_free(g); + return result; +} +``` diff --git a/docs/api/en/c/3_qis/1_statevector.md b/docs/api/en/c/3_qis/1_statevector.md index 9bc3e97c..c5ee415a 100644 --- a/docs/api/en/c/3_qis/1_statevector.md +++ b/docs/api/en/c/3_qis/1_statevector.md @@ -8,6 +8,8 @@ The `CStatevector*` handle is the pure-state simulator: the quantum state is rep ### statevector_new(num_qubits) +Returns `NULL` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + ```c struct CStatevector *statevector_new(uintptr_t num_qubits); ``` diff --git a/docs/api/en/c/3_qis/2_density_matrix.md b/docs/api/en/c/3_qis/2_density_matrix.md index d66548f6..94dc372f 100644 --- a/docs/api/en/c/3_qis/2_density_matrix.md +++ b/docs/api/en/c/3_qis/2_density_matrix.md @@ -8,6 +8,8 @@ The `CDensityMatrix*` handle is the mixed-state simulator: the quantum state is ### density_matrix_new(num_qubits) +Returns `NULL` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + ```c struct CDensityMatrix *density_matrix_new(uintptr_t num_qubits); ``` @@ -20,6 +22,8 @@ Returns: a newly allocated `CDensityMatrix*`; free it with `density_matrix_free` ### density_matrix_maximally_mixed(num_qubits) +Returns `NULL` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + ```c struct CDensityMatrix *density_matrix_maximally_mixed(uintptr_t num_qubits); ``` @@ -32,6 +36,8 @@ Returns: a newly allocated `CDensityMatrix*`; free it with `density_matrix_free` ### density_matrix_zeros(num_qubits) +Returns `NULL` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + ```c struct CDensityMatrix *density_matrix_zeros(uintptr_t num_qubits); ``` diff --git a/docs/api/en/c/3_qis/3_density_matrix_noise.md b/docs/api/en/c/3_qis/3_density_matrix_noise.md index 74b85ee7..f6b24cc2 100644 --- a/docs/api/en/c/3_qis/3_density_matrix_noise.md +++ b/docs/api/en/c/3_qis/3_density_matrix_noise.md @@ -8,6 +8,8 @@ The `CDensityMatrixNoise*` handle is the noisy mixed-state simulator: it layers ### density_matrix_noise_new(num_qubits, noise_model) +Returns `NULL` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + ```c struct CDensityMatrixNoise *density_matrix_noise_new(uintptr_t num_qubits, const struct CNoiseModel *noise_model); @@ -248,7 +250,7 @@ Takes the ideal probability distribution and applies the readout errors register - `ptr` (`const CDensityMatrixNoise*`): noisy-simulator handle. - `buffer` (`double*`): output buffer. - `len` (`uintptr_t`): buffer length; must equal `density_matrix_noise_probabilities_with_readout_len`. -- `qubits` (`const uint32_t*`): array of qubits to apply readout errors to; may be NULL when `qubit_len` is 0, in which case the result matches `density_matrix_noise_probabilities`. +- `qubits` (`const uint32_t*`): storage positions on which to apply readout errors. Circuit-bound states look up noise using the circuit ID at each position; unbound states use identity IDs. The full output distribution retains storage order. May be NULL when `qubit_len` is 0, in which case the result matches `density_matrix_noise_probabilities`. - `qubit_len` (`uintptr_t`): number of qubits. Returns: `0` on success; `-1` NULL pointers; `-2` out-of-bounds qubit; `-8` when `len` does not match the actual count. diff --git a/docs/api/en/c/3_qis/6_pauli.md b/docs/api/en/c/3_qis/6_pauli.md index d42ac6f3..e94853e9 100644 --- a/docs/api/en/c/3_qis/6_pauli.md +++ b/docs/api/en/c/3_qis/6_pauli.md @@ -132,13 +132,15 @@ Returns: 1 when they commute; 0 otherwise; -1 for NULL handles; -8 when the qubi ### pauli_string_matrix_len(ptr) -Returns the side length of the dense matrix (`2^N`); 0 for NULL. +Returns the side length of the dense matrix (`2^N`); 0 for NULL or an unrepresentable side length. ### pauli_string_matrix(ptr, buffer, len) Copies the `2^N × 2^N` dense matrix into `buffer` in row-major order (`Complex64` values). `len` must equal `pauli_string_matrix_len(ptr) * pauli_string_matrix_len(ptr)`. -Returns: 0 on success; -1 for NULL pointers; -8 when `len` does not match the matrix element count. +Returns: 0 on success; -1 for NULL pointers; -7 for unrepresentable element/byte counts or allocation failure; -8 when `len` does not match the matrix element count. Errors leave the buffer unchanged. + +A representable side does not guarantee the complete matrix can be allocated. Check for overflow before computing `dim * dim`. --- @@ -169,6 +171,7 @@ Returns: 0 on success; -1 when `ptr` or `out` is NULL, or when either array is N ## Example ```c +#include #include #include #include "cqlib_c.h" @@ -192,6 +195,11 @@ int main(void) { struct CPauliString *zz = pauli_string_parse("ZZI"); int32_t commutes = pauli_string_commutes_with(ps, zz); /* 0 (X and Z anticommute on qubit 2) */ + printf("%s: qubits=%" PRIuPTR ", p2=%u, p0=%u\n", text, n, + (unsigned)p2, (unsigned)p0); + printf("x_mask=%" PRIuPTR ", z_mask=%" PRIuPTR ", commutes=%" PRId32 "\n", + x_mask, z_mask, commutes); + /* 4. Two-step read of the 8x8 dense matrix */ uintptr_t dim = pauli_string_matrix_len(ps); /* 8 */ Complex64 *matrix = malloc(dim * dim * sizeof(Complex64)); diff --git a/docs/api/en/c/3_qis/7_hamiltonian.md b/docs/api/en/c/3_qis/7_hamiltonian.md index 08f1b73b..6688f7ec 100644 --- a/docs/api/en/c/3_qis/7_hamiltonian.md +++ b/docs/api/en/c/3_qis/7_hamiltonian.md @@ -99,9 +99,11 @@ Returns: 1 when all terms commute; 0 otherwise; -1 for NULL. ### hamiltonian_to_matrix_len(ptr) / hamiltonian_to_matrix(ptr, buffer, len) -Two-step read of the dense matrix: `*_len` returns the side length `2^N` (0 for NULL), and the fill function copies the `2^N × 2^N` matrix into `buffer` in row-major order (`Complex64` values). `len` must equal the square of the side length. +Two-step read of the dense matrix: `*_len` returns the side length `2^N` (0 for NULL or an unrepresentable side length), and the fill function copies the `2^N × 2^N` matrix into `buffer` in row-major order (`Complex64` values). `len` must equal the square of the side length. -Returns (fill function): 0 on success; -1 for NULL pointers; -8 when `len` does not match the matrix element count. +Returns (fill function): 0 on success; -1 for NULL pointers; -7 for unrepresentable element/byte counts or allocation failure; -8 when `len` does not match the matrix element count. Errors leave the buffer unchanged. + +A representable side does not guarantee the complete matrix can be allocated. Check for overflow before computing `dim * dim`. --- @@ -212,6 +214,7 @@ Returns: a new `CCircuit*` on success (free with `circuit_free`); NULL on NULL i ## Example ```c +#include #include #include #include "cqlib_c.h" @@ -230,6 +233,8 @@ int main(void) { uintptr_t nq = hamiltonian_num_qubits(ham); /* 2 */ uintptr_t nt = hamiltonian_num_terms(ham); /* 2 */ int32_t commute = hamiltonian_all_terms_commute(ham); /* 1 (single-qubit terms commute) */ + printf("qubits=%" PRIuPTR ", terms=%" PRIuPTR ", commute=%" PRId32 "\n", + nq, nt, commute); hamiltonian_simplify(ham); /* 3. Two-step read of the 4x4 dense matrix */ @@ -280,3 +285,86 @@ int main(void) { ``` Hamiltonians serve as observables in the error-mitigation workflows (see [Zero-Noise Extrapolation](../6_error_mitigation/1_zne.md) and [Virtual Distillation](../6_error_mitigation/2_virtual_distillation.md)); their expectation values can be computed directly with the statevector simulator (see [Statevector](1_statevector.md)). + + +## Checked sparse Pauli algebra + +`CHamiltonian` also represents general non-Hermitian sparse operators. These new functions follow the error/output conventions of the [fermionic binding](10_fermion.md): success is 0, object outputs are independent handles delivered through `**out`, and errors leave outputs and inputs unchanged. Input Pauli handles are borrowed and copied. Legacy consuming `from_pauli`, in-place `scale` and approximate-pruning `simplify` remain unchanged. + +```c +typedef struct CHamiltonianTerm { + const CPauliString *pauli; + Complex64 coefficient; +} CHamiltonianTerm; + +int32_t hamiltonian_identity(size_t num_qubits, CHamiltonian **out); + +int32_t hamiltonian_from_terms(size_t num_qubits, + const CHamiltonianTerm *terms, + size_t len, + CHamiltonian **out); + +int32_t hamiltonian_copy(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_normalized(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_normalized_hermitian(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_add(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_sub(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_mul(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_scaled(const CHamiltonian *ptr, + Complex64 factor, + CHamiltonian **out); + +int32_t hamiltonian_adjoint(const CHamiltonian *ptr, CHamiltonian **out); + +int32_t hamiltonian_tensor(const CHamiltonian *left, + const CHamiltonian *right, + CHamiltonian **out); + +int32_t hamiltonian_remap_qubits(const CHamiltonian *ptr, + const size_t *mapping, + size_t len, + size_t target_width, + CHamiltonian **out); + +int32_t hamiltonian_chop(CHamiltonian *ptr, double atol); + +int32_t hamiltonian_equiv(const CHamiltonian *left, + const CHamiltonian *right, + double atol, + uint8_t *out); + +int32_t hamiltonian_is_hermitian(const CHamiltonian *ptr, double atol, uint8_t *out); + +int32_t hamiltonian_get_term(const CHamiltonian *ptr, + size_t index, + CPauliString **out_pauli, + Complex64 *out_coefficient); +``` + +| Functions | Behavior | +| --- | --- | +| `identity/from_terms` | Identity supports scalar one on zero qubits; empty terms retain width. Batch construction validates widths/coefficients, absorbs Pauli phases, merges duplicates and removes only exact zeros. | +| `copy/get_term` | Independent storage copies. get_term returns a stored Pauli copy and coefficient without normalizing; free the Pauli with pauli_string_free. Zero-width Paulis are valid. Bad indices return -2. | +| `normalized` | Validated, exactly merged copy without near-zero pruning. | +| `normalized_hermitian` | After normalization, projects imaginary parts of magnitude <=1e-10 to zero; larger parts return -8. Retains every nonzero real coefficient. | +| `add/sub/mul/scaled/adjoint` | Call core checked methods; validate input/result coefficients. Nonfinite values and overflow return -8. Binary arithmetic requires equal widths; mul applies the right operand first. | +| `tensor` | Left tensor right; right occupies low qubits. Widths add; arithmetic width overflow returns -8. | +| `remap_qubits` | mapping[source]=destination; length equals input width; destinations are unique and less than target_width. Unused qubits are identity. This is not a fermionic permutation. | +| `chop` | Normalize in place then remove coefficients with magnitude <=atol; failure is atomic. | +| `equiv/is_hermitian` | Write 0/1. atol must be finite/nonnegative; 0 is exact. equiv requires equal widths; Hermiticity compares with the adjoint without projection. | + +Free object results with `hamiltonian_free`; supply an empty, valid output slot. Required NULL pointers return -1; invalid parameters, widths, coefficients or tolerances return -8. Unrepresentable materialized Pauli widths in identity/tensor/remap return -7. Zero sums may retain larger widths without materializing bit vectors. + +atol is a coefficient tolerance. On normalized sums, `is_hermitian` bounds `2*abs(imag) <= atol`; this is independent of the projection threshold in `normalized_hermitian`. Sparse algebra builds no dense matrix and never implicitly calls legacy simplify. diff --git a/docs/api/en/c/4_compile/6_decompose_resynthesis.md b/docs/api/en/c/4_compile/6_decompose_resynthesis.md index fcffb315..e7f26906 100644 --- a/docs/api/en/c/4_compile/6_decompose_resynthesis.md +++ b/docs/api/en/c/4_compile/6_decompose_resynthesis.md @@ -1,6 +1,6 @@ # Decompose / Resynthesis (C) -This page covers the circuit-level decomposition passes (circuit-gate definition expansion `decompose_expand_definitions`, matrix-backed unitary synthesis `decompose_unitaries`, multi-controlled gate rewriting `decompose_mc_gates`), two-qubit block resynthesis `resynthesize_two_qubit_blocks`, the numeric unitary-matrix synthesis primitives (one-qubit / two-qubit), unitary synthesis targets `decompose_unitary_target_*`, KAK (Weyl) decomposition, target-basis lowering `target_basis_lowerer_*`, and device lowering `decompose_lower_to_device`. Decomposition is layered by the representation each operation carries: definition expansion runs before numeric synthesis, so unitary gates that ship their own implementation circuit are expanded before entering matrix synthesis. Matrix inputs use `Complex64` (`{double re; double im}` interleaved pairs, row-major); the layout is described in [Unitary Gates](../0_circuit/6_gate_unitary.md). Error codes, string and handle ownership conventions follow the [Overview](../0_overview.md). +This page covers the circuit-level decomposition passes (circuit-gate definition expansion `decompose_expand_definitions`, matrix-backed unitary synthesis `decompose_unitaries`, multi-controlled gate rewriting `decompose_mc_gates`), two-qubit block resynthesis `resynthesize_two_qubit_blocks`, the numeric unitary-matrix synthesis primitives (including multi-qubit Block-ZXZ), unitary synthesis targets `decompose_unitary_target_*`, KAK (Weyl) decomposition, target-basis lowering `target_basis_lowerer_*`, and device lowering `decompose_lower_to_device`. Decomposition is layered by the representation each operation carries: definition expansion runs before numeric synthesis, so unitary gates that ship their own implementation circuit are expanded before entering matrix synthesis. Matrix inputs use `Complex64` (`{double re; double im}` interleaved pairs, row-major); the layout is described in [Unitary Gates](../0_circuit/6_gate_unitary.md). Error codes, string and handle ownership conventions follow the [Overview](../0_overview.md). --- @@ -25,13 +25,22 @@ KAK local-factor tags (the `factor` parameter of `kak_decomposition_local_factor | `KAK_FACTOR_K2L` | 2 | `k2l` (left local factor, applied before the interaction). | | `KAK_FACTOR_K2R` | 3 | `k2r` (right local factor, applied before the interaction). | +Block-ZXZ optimization flags (bitmask for `block_zxz_decompose` and `CUnitaryDecomposeConfig.block_zxz_options`): + +| Constant | Value | Meaning | +| --- | --- | --- | +| `BLOCK_ZXZ_OPT_A1` | 1 | Absorb two boundary `CX` gates per recursive layer. | +| `BLOCK_ZXZ_OPT_A2` | 2 | Transfer a diagonal remainder between consecutive two-qubit leaves. | +| `BLOCK_ZXZ_OPT_A2_FORCE` | 4 | Permit A.2 on block-diagonal inputs when `BLOCK_ZXZ_OPT_A2` is set. | +| `BLOCK_ZXZ_OPT_ALL` | 3 | Default optimizations (`BLOCK_ZXZ_OPT_A1 | BLOCK_ZXZ_OPT_A2`), with automatic block-diagonal handling. | + --- ## Configuration Construction ### decompose_unitary_config_default() -Returns the default unitary-decompose configuration by value: `recurse_control_flow=1` (recurse into control-flow bodies). +Returns the default unitary-decompose configuration by value: `recurse_control_flow=1` (recurse into control-flow bodies), `has_block_zxz_options=1`, and `block_zxz_options=BLOCK_ZXZ_OPT_ALL` (both Block-ZXZ CX reductions enabled for three-or-more-qubit unitary gates). ```c struct CUnitaryDecomposeConfig decompose_unitary_config_default(void); @@ -217,6 +226,29 @@ Returns: a new `CCircuit*` on success (free with `circuit_free`); NULL when `cir ## Numeric Unitary Synthesis Primitives +### block_zxz_decompose(matrix, dim, atol, options) + +```c +struct CCircuit *block_zxz_decompose(const Complex64 *matrix, uintptr_t dim, + double atol, uint8_t options); +``` + +Supply a row-major square unitary. The caller owns an aligned buffer of at +least `dim * dim` initialized `Complex64` values, each a real/imaginary +pair of doubles. `matrix[row * dim + column]` is the corresponding element. +The function borrows the buffer during the call. `dim` is the side length +and must be a power of two in `[2, 2^20]`. The API checks the computed byte +extent before reading. The caller supplies the storage for that extent. +`atol` is a finite nonnegative absolute tolerance. + +Pass `BLOCK_ZXZ_OPT_ALL` for the default, zero for unoptimized synthesis, +or combine `BLOCK_ZXZ_OPT_A1` and `BLOCK_ZXZ_OPT_A2` by bitwise OR. +Add `BLOCK_ZXZ_OPT_A2_FORCE` to permit enabled A.2 on block-diagonal inputs. +Success returns an owned circuit including the global phase. Release it +with `circuit_free`. A null input, invalid shape, overflowing extent, +unknown option bits, invalid tolerance, non-finite or non-unitary matrix, +or numerical failure returns `NULL`. + ### synthesize_numeric_1q_unitary(matrix, out) Synthesizes a 2x2 unitary matrix into Cqlib's `U` convention: the represented matrix is `exp(i * global_phase) * U(theta, phi, lambda)`. `matrix` points at 4 row-major `Complex64` elements. @@ -781,14 +813,18 @@ Returns: a new `CCircuit*` on success (free with `circuit_free`); NULL when any ```c typedef struct CUnitaryDecomposeConfig { uint8_t recurse_control_flow; - uint8_t _reserved[7]; + uint8_t has_block_zxz_options; + uint8_t block_zxz_options; + uint8_t _reserved[5]; } CUnitaryDecomposeConfig; ``` | Field | Type | Meaning | | --- | --- | --- | | `recurse_control_flow` | `uint8_t` | 1 recurses into control-flow bodies, 0 does not. | -| `_reserved[7]` | `uint8_t[7]` | Padding that keeps the struct layout stable. | +| `has_block_zxz_options` | `uint8_t` | Nonzero uses `block_zxz_options`; 0 (including zero-initialized structs) selects `BLOCK_ZXZ_OPT_ALL`. | +| `block_zxz_options` | `uint8_t` | Bitmask of `BLOCK_ZXZ_OPT_*` switches applied to three-or-more-qubit Block-ZXZ synthesis when `has_block_zxz_options != 0` (`BLOCK_ZXZ_OPT_ALL` by default). | +| `_reserved[5]` | `uint8_t[5]` | Padding that keeps the struct layout stable. | ### CMcGateDecomposeConfig diff --git a/docs/api/en/c/5_visualization/3_state_plots.md b/docs/api/en/c/5_visualization/3_state_plots.md index 8757ef43..fe296975 100644 --- a/docs/api/en/c/5_visualization/3_state_plots.md +++ b/docs/api/en/c/5_visualization/3_state_plots.md @@ -76,6 +76,8 @@ Failure scenarios: same as [plot_bloch_multivector](#plot_bloch_multivectorstate Plots Pauli-basis expectation values as a bar chart. Labels are tensor products of `I`, `X`, `Y`, `Z`, for `4^n` bars in total where `n` is the qubit count; non-negative and negative bars use different colors. Rotated x-axis labels are drawn only when the bar count does not exceed `64`. +By default, labels follow `PauliString`: the highest-index qubit is on the left and qubit 0 is on the right. For example, `IX` measures X on qubit 0 of a two-qubit state. Enabling `reverse_bits` reverses the characters in each label without changing the corresponding expectation value. + ```c char *plot_state_paulivec(const struct CStatevector *state, const struct CStatePlotOptions *options); diff --git a/docs/api/en/c/6_error_mitigation/0_overview.md b/docs/api/en/c/6_error_mitigation/0_overview.md index 7b53d4ba..5c82f497 100644 --- a/docs/api/en/c/6_error_mitigation/0_overview.md +++ b/docs/api/en/c/6_error_mitigation/0_overview.md @@ -56,7 +56,7 @@ Mitigation flows obtain expectation estimates through this callback. The contrac - **Pointer validity**: `circuit`, `hamiltonian` and all out pointers are valid only for the duration of the callback; do not keep using them or store them beyond the callback. - **hamiltonian ownership**: the `hamiltonian` handle is owned by the library and must not be freed by the callback. The Hamiltonian the callback receives may already have been expanded to the width of the folded/copy circuit as required by the flow. -- **Out writes**: the callback must write the expectation value through `expectation`; write the variance through `variance` when known, NaN otherwise. In the virtual distillation denominator estimate, `hamiltonian` is NULL — treat it as "no observable". +- **Out writes**: the callback must write the expectation value through `expectation`; write the variance through `variance` when known, NaN otherwise. In virtual distillation both the numerator and the denominator estimates pass a non-NULL `hamiltonian`: the numerator observable acts on the first copy's qubits and carries `X` on the ancillary qubit, while the denominator observable carries only `X` on the ancillary qubit (identities elsewhere). - **shots semantics**: `shots == 0` means "not specified" and the callback decides the sampling scale; a non-zero value is the shot count suggested by the caller. Inside the callback you can freely call simulator interfaces (e.g. `statevector_from_circuit` + `statevector_expectation` from the [Statevector](../3_qis/1_statevector.md) page) to compute the estimate. diff --git a/docs/api/en/c/6_error_mitigation/2_virtual_distillation.md b/docs/api/en/c/6_error_mitigation/2_virtual_distillation.md index 266ebd87..61f7116b 100644 --- a/docs/api/en/c/6_error_mitigation/2_virtual_distillation.md +++ b/docs/api/en/c/6_error_mitigation/2_virtual_distillation.md @@ -44,11 +44,11 @@ Returns `int32_t`: 0 on success; -1 (`ptr` NULL); -8 (`copies` less than 2). ### virtual_distillation_build_circuit(ptr) -Builds the copy-swap circuit used by the virtual distillation protocol: the base circuit is first decomposed into gates, then prepared `copies` times side by side — copy `i` is shifted onto the qubit range starting at `i × base width`, with no overlap between copies — and finally a `SWAP` is inserted bitwise between the first copy and each of the other copies. +Builds the copy-swap circuit used by the virtual distillation protocol (a Hadamard-test circuit): the base circuit is first decomposed into gates, then prepared `copies` times side by side — copy `i` is shifted onto the qubit range starting at `i × base width`, with no overlap between copies — then one ancillary qubit (the last qubit) is prepared in `|+⟩` by a Hadamard gate, and finally a ladder of `SWAP`s between adjacent copies, each controlled by the ancillary qubit (CSWAP), implements the derangement of the copies. - `ptr` (`const struct CVirtualDistillation *`): the virtual distillation handle. -The circuit width is `copies × base width` (the base width being the width of the decomposed circuit); the operation count is `copies` copies of the base operations plus `(copies - 1) × base width` `SWAP` gates. +The circuit width is `copies × base width + 1` (the base width being the width of the decomposed circuit; the last qubit is the ancillary qubit); the operation count is `copies` copies of the base operations plus one `H` and `(copies - 1) × base width` controlled `SWAP` gates. Returns `struct CCircuit *`: an owned handle of the copy-swap circuit, freed with `circuit_free`; NULL when `ptr` is NULL or construction fails. @@ -56,11 +56,11 @@ Returns `struct CCircuit *`: an owned handle of the copy-swap circuit, freed wit ## Numerator and Denominator -The estimator callback distinguishes the two circuits through the `hamiltonian` parameter: the numerator circuit carries the observable, the denominator circuit has none. +The estimator callback receives a non-NULL `hamiltonian` for both circuits and tells them apart by content: the numerator observable acts on the first copy's qubits and carries `X` on the ancillary qubit; the denominator observable carries only `X` on the ancillary qubit (identities elsewhere). ### virtual_distillation_run_numerator_circuit(ptr, hamiltonian, shots, estimator, out_mean, out_variance) -Runs the numerator circuit through the estimator callback to estimate `Tr(O ρ^M)`. The estimator receives the copy-swap circuit, a Hamiltonian expanded to the full copy-swap width, and `shots`. Expansion rule: the original Pauli terms keep their qubit indices, phases and coefficients; the new higher-index qubits are padded with `Z`. +Runs the numerator circuit through the estimator callback to estimate `Tr(O ρ^M)`. The estimator receives the copy-swap circuit, a Hamiltonian expanded to the full copy-swap width, and `shots`. Expansion rule: the original Pauli terms keep their qubit indices (i.e. they act on the first copy), phases and coefficients; the remaining copies are padded with `I`, and an `X` is appended on the ancillary qubit (the last qubit). - `ptr` (`const struct CVirtualDistillation *`): the virtual distillation handle. - `hamiltonian` (`const struct CHamiltonian *`): the observable; its qubit count must match the base circuit width, see [Hamiltonian](../3_qis/7_hamiltonian.md) for construction. @@ -73,7 +73,7 @@ Returns `int32_t`: 0 on success; -1 (`ptr`, `hamiltonian`, `out_mean` or `out_va ### virtual_distillation_run_denominator_circuit(ptr, shots, estimator, out_mean, out_variance) -Runs the denominator circuit through the estimator callback to estimate `Tr(ρ^M)`. The estimator receives the copy-swap circuit, a NULL Hamiltonian, and `shots`. +Runs the denominator circuit through the estimator callback to estimate `Tr(ρ^M)`. The estimator receives the copy-swap circuit, a Hamiltonian with `X` on the ancillary qubit (the last qubit) and identities elsewhere, and `shots`. - `ptr` (`const struct CVirtualDistillation *`): the virtual distillation handle. - `shots` (`uintptr_t`): the shot count forwarded to the estimator. @@ -85,7 +85,7 @@ Returns `int32_t`: 0 on success; -1 (`ptr`, `out_mean` or `out_variance` NULL); ### virtual_distillation_build_copy_swap_circuit(ptr) -Constructs the copy-swap circuit from the base circuit: the base circuit is first decomposed into gates, then prepared `copies` times side by side — copy `i` is shifted onto the qubit range starting at `i × base width`, with no overlap between copies — and finally a `SWAP` is inserted bitwise between the first copy and each of the other copies. The circuit width is `copies × base width` (the base width being the width of the decomposed circuit); the operation count is `copies` copies of the base operations plus `(copies - 1) × base width` `SWAP` gates. +Constructs the copy-swap circuit from the base circuit: the base circuit is first decomposed into gates, then prepared `copies` times side by side — copy `i` is shifted onto the qubit range starting at `i × base width`, with no overlap between copies — then one ancillary qubit (the last qubit) is prepared in `|+⟩` by a Hadamard gate, and finally a ladder of `SWAP`s between adjacent copies, each controlled by the ancillary qubit, implements the derangement of the copies. The circuit width is `copies × base width + 1` (the base width being the width of the decomposed circuit); the operation count is `copies` copies of the base operations plus one `H` and `(copies - 1) × base width` controlled `SWAP` gates. - `ptr` (`const struct CVirtualDistillation *`): the virtual distillation handle. @@ -119,20 +119,21 @@ The variance is combined with a first-order Taylor approximation, assuming the n #include #include "cqlib_c.h" -/* The numerator circuit carries the observable, the denominator does not */ +/* Both the numerator and the denominator carry a Hamiltonian — the + numerator acts on the first copy's qubits and carries X on the + ancillary qubit, the denominator carries only X on the ancillary + qubit; simulate the circuit exactly and evaluate the observable */ static void estimate(const struct CCircuit *circuit, const struct CHamiltonian *hamiltonian, uintptr_t shots, double *expectation, double *variance) { - if (hamiltonian != NULL) { - *expectation = 1.5; - *variance = 0.25; - } else { - *expectation = 2.0; - *variance = 1.0; - } - (void)circuit; + struct CStatevector *sv = statevector_from_circuit(circuit); + double value = 0.0; + statevector_expectation(sv, hamiltonian, &value); + statevector_free(sv); + *expectation = value; + *variance = 0.0; (void)shots; } @@ -142,13 +143,13 @@ int main(void) { circuit_x(qc, 0); struct CVirtualDistillation *vd = virtual_distillation_new(qc, 2); - /* Copy-swap circuit: width = 2 × 1 = 2 */ + /* Copy-swap circuit: width = 2 × 1 + 1 = 3 */ struct CCircuit *copy_swap = virtual_distillation_build_circuit(vd); struct CPauliString *z = pauli_string_parse("Z"); struct CHamiltonian *obs = hamiltonian_from_pauli(z); /* takes ownership of z */ - /* mu_vd = 1.5 / 2.0 = 0.75 */ + /* For rho = |1><1|: numerator Tr(Z rho^2) = -1, denominator Tr(rho^2) = 1 */ double mean = 0.0, variance = 0.0; virtual_distillation_run_vd(vd, obs, 3, 2, estimate, &mean, &variance); printf("VD estimate: %f\n", mean); diff --git a/docs/api/en/c/6_error_mitigation/3_unified.md b/docs/api/en/c/6_error_mitigation/3_unified.md index d5efbb7e..82392598 100644 --- a/docs/api/en/c/6_error_mitigation/3_unified.md +++ b/docs/api/en/c/6_error_mitigation/3_unified.md @@ -72,32 +72,27 @@ Returns `int32_t`: 0 on success; -1 (`ptr`, `out_expectation` or `out_variance` ## Example -A complete flow with the virtual distillation method (the callback branches on the numerator circuit carrying the observable vs. the denominator circuit having none, see the [module overview](0_overview.md)): +A complete flow with the virtual distillation method (both the numerator and the denominator callbacks receive a non-NULL Hamiltonian, see the [module overview](0_overview.md)): ```c #include #include "cqlib_c.h" -/* Estimator callback: the numerator circuit carries the observable - (exact simulation); the denominator circuit has none */ +/* Estimator callback: both the numerator and the denominator carry a + Hamiltonian (the numerator acts on the first copy's qubits and carries + X on the ancillary qubit; the denominator carries only X on the + ancillary qubit) — simulate the circuit exactly and evaluate it */ static void estimate(const struct CCircuit *circuit, const struct CHamiltonian *hamiltonian, uintptr_t shots, double *expectation, double *variance) { - if (hamiltonian != NULL) { - struct CStatevector *sv = statevector_from_circuit(circuit); - double value = 0.0; - statevector_expectation(sv, hamiltonian, &value); - statevector_free(sv); - *expectation = value; - *variance = 0.0; - } else { - /* Denominator Tr(rho^M): estimated from measurement outcomes by a - sampling estimator; a sample value is returned here */ - *expectation = 1.0; - *variance = 0.0; - } + struct CStatevector *sv = statevector_from_circuit(circuit); + double value = 0.0; + statevector_expectation(sv, hamiltonian, &value); + statevector_free(sv); + *expectation = value; + *variance = 0.0; (void)shots; } diff --git a/docs/api/en/python/0_circuit/0_overview.md b/docs/api/en/python/0_circuit/0_overview.md index dec0bf09..0571912e 100644 --- a/docs/api/en/python/0_circuit/0_overview.md +++ b/docs/api/en/python/0_circuit/0_overview.md @@ -111,6 +111,7 @@ This page gives a brief description of terms commonly used in the `cqlib.circuit | `ClassicalVar` | [Classical / Control Flow](9_classical_control_flow.md) | A mutable classical storage handle, created by `Circuit.var()`. | | `ClassicalValue` | [Classical / Control Flow](9_classical_control_flow.md) | An immutable classical value, usually produced by measurement. | | `Measurement` | [Classical / Control Flow](9_classical_control_flow.md) | A measurement receipt, containing the measured values and the order of the measured qubits. | +| `ClassicalDataOp` | [Classical / Control Flow](9_classical_control_flow.md) | The instruction form of a classical data operation (a store or a measurement result write), obtained from `Instruction.classical_data`. | | `ClassicalExpr` | [Classical / Control Flow](9_classical_control_flow.md) | A typed classical expression AST, used for conditions, comparisons, bit extraction and expression composition. | | `ClassicalControlOp` | [Classical / Control Flow](9_classical_control_flow.md) | The structured control flow IR, including `if`, `while`, `for`, `switch`, `break` and `continue`. | | `ValueControlBody` | [Classical / Control Flow](9_classical_control_flow.md) | A construction-layer control flow body, containing several `ValueOperation`s. | diff --git a/docs/api/en/python/0_circuit/4_operation_instruction.md b/docs/api/en/python/0_circuit/4_operation_instruction.md index 59ba67c5..566b516f 100644 --- a/docs/api/en/python/0_circuit/4_operation_instruction.md +++ b/docs/api/en/python/0_circuit/4_operation_instruction.md @@ -71,7 +71,13 @@ delay_inst = Instruction.delay() | `is_classical_data` | `bool` | Whether it is an instruction related to classical data. | | `is_delay` | `bool` | Whether it is a delay instruction. | | `standard_gate` | `StandardGate / None` | When the instruction is a standard gate, return the internal standard gate object. | +| `mc_gate` | `MCGate / None` | When the instruction is a multi-controlled gate, return the internal `MCGate` object. | +| `unitary_gate` | `UnitaryGate / None` | When the instruction is a user-defined unitary gate, return the internal `UnitaryGate` object. | +| `circuit_gate` | `CircuitGate / None` | When the instruction is a sub-circuit composite gate, return the internal `CircuitGate` object. | | `directive` | `Directive / None` | When the instruction is a `Directive`, return the internal directive object. | +| `classical_data` | `ClassicalDataOp / None` | When the instruction is a classical data operation, return the internal `ClassicalDataOp` object. | + +Gate objects returned by these payload accessors carry no bound parameters: parameters belong to the operation layer (see `ValueOperation.params`), so the returned gates always have an empty parameter list. Note that `Instruction` provides no `classical_control` payload accessor: the storage-layer control flow operation inlines circuit-internal handles, and its content can only be read at the construction layer through `ValueInstruction.classical_control`. --- @@ -98,7 +104,11 @@ delay_inst = Instruction.delay() | `instruction_type` | `str` | The instruction category, with the same values as `Instruction.instruction_type`; it is `"classical_control"` when control flow is wrapped. | | `is_standard` / `is_mcgate` / `is_unitary` / `is_circuit_gate` / `is_directive` / `is_classical_data` / `is_delay` | `bool` | Category check attributes with the same names as on `Instruction`; all are `False` when control flow is wrapped. | | `standard_gate` | `StandardGate / None` | When a standard gate instruction is wrapped, return the internal standard gate object. | +| `mc_gate` | `MCGate / None` | When a multi-controlled gate instruction is wrapped, return the internal `MCGate` object. | +| `unitary_gate` | `UnitaryGate / None` | When a user-defined unitary gate instruction is wrapped, return the internal `UnitaryGate` object. | +| `circuit_gate` | `CircuitGate / None` | When a sub-circuit composite gate instruction is wrapped, return the internal `CircuitGate` object. | | `directive` | `Directive / None` | When a `Directive` instruction is wrapped, return the internal directive object. | +| `classical_data` | `ClassicalDataOp / None` | When a classical data instruction is wrapped, return the internal `ClassicalDataOp` object. | --- diff --git a/docs/api/en/python/0_circuit/9_classical_control_flow.md b/docs/api/en/python/0_circuit/9_classical_control_flow.md index 2795589d..e5766ec1 100644 --- a/docs/api/en/python/0_circuit/9_classical_control_flow.md +++ b/docs/api/en/python/0_circuit/9_classical_control_flow.md @@ -5,6 +5,7 @@ - `cqlib.circuit.ClassicalVar` - `cqlib.circuit.ClassicalValue` - `cqlib.circuit.Measurement` +- `cqlib.circuit.ClassicalDataOp` - `cqlib.circuit.ClassicalExpr` - `cqlib.circuit.ClassicalControlOp` - `cqlib.circuit.ValueControlBody` @@ -15,6 +16,7 @@ from cqlib.circuit import ( CircuitId, ClassicalType, ClassicalExpr, + ClassicalDataOp, ClassicalControlOp, ValueControlBody, ValueSwitchCase, @@ -35,6 +37,7 @@ Classical data and control flow objects fall into the following categories: | `ClassicalVar` | A mutable classical variable handle, created by `Circuit.var()`. | | `ClassicalValue` | An immutable classical value handle, usually produced by measurement. | | `Measurement` | A measurement receipt, recording the measurement result handle and the order of the measured qubits. | +| `ClassicalDataOp` | The instruction form of a classical data operation (a store or a measurement result write), obtained from `Instruction.classical_data`. | | `ClassicalExpr` | A side-effect-free classical expression, which can represent literals, variable reads, comparisons and logical composition. | | `ClassicalControlOp` | A low-level control flow object, used to represent `if`, `while`, `for`, `switch`, `break` and `continue`. | | `ValueControlBody` | The operation sequence in a control flow branch body or loop body. | @@ -238,6 +241,30 @@ condition = single.expr().to_bool() --- +## `ClassicalDataOp` + +`ClassicalDataOp` is the instruction form of a classical data operation: a store into a mutable classical variable, or a measurement producing an immutable classical value. It is not constructed directly; instances are obtained from the `classical_data` attribute of `Instruction` or `ValueInstruction`. + +| Attribute | Type | Description | +|---|---|---| +| `kind` | `str` | The operation kind: `"store"`, `"measure_bit"` or `"measure_bits"`. | +| `target` | `ClassicalVar / None` | The store target variable when `kind` is `"store"`. | +| `value` | `ClassicalExpr / None` | The stored expression when `kind` is `"store"`. | +| `result` | `ClassicalValue / None` | The immutable value receiving the result when `kind` is `"measure_bit"` or `"measure_bits"`. | + +```python +from cqlib import Circuit + +circuit = Circuit(2) +circuit.measure_bits([0, 1]) + +data = circuit.operations[0].instruction.classical_data +print(data.kind) # measure_bits +print(data.result) # the produced ClassicalValue +``` + +--- + ## `ClassicalExpr` `ClassicalExpr` describes classical computation relations, such as reading variables, reading measurement values, constructing literals, performing logical operations, comparing expressions, conditional selection, bit extraction and bit concatenation. diff --git a/docs/api/en/python/1_ir/3_qasm3.md b/docs/api/en/python/1_ir/3_qasm3.md index ae0e5c87..6b1982cb 100644 --- a/docs/api/en/python/1_ir/3_qasm3.md +++ b/docs/api/en/python/1_ir/3_qasm3.md @@ -143,6 +143,7 @@ The following OpenQASM 3.0 features are not supported in the current implementat - Subroutines and external calls: `def` subroutines, `extern` - Hardware-related: hardware qubits, `output` declarations, and `input` declarations other than angle and floating-point - Other statements: `alias`, `pragma`, annotations, legacy declarations +- Program termination: `end` is explicitly rejected in every scope, including unreachable branches and zero-iteration loops - Gate modifiers: `negctrl`, `pow`; `ctrl` and `inv` are available only when a corresponding implementation exists for the target gate - Some standard gates: `ch`, `cp`, `cu`, `cswap` - Control flow: a lowering path for `while` exists in the implementation, but loops with a runtime condition are currently rejected by the semantic check; `for` supports only the statically expanded form whose range is constant diff --git a/docs/api/en/python/3_qis/0_overview.md b/docs/api/en/python/3_qis/0_overview.md index e92b10c1..2564dd96 100644 --- a/docs/api/en/python/3_qis/0_overview.md +++ b/docs/api/en/python/3_qis/0_overview.md @@ -29,6 +29,8 @@ All four simulators provide a `from_circuit()` static method, which simulates a ### Observables and time evolution +[`FermionicOp` and `JordanWignerMapper`](10_fermion.md) provide general fermionic algebra, excitation generators and mappings to Pauli sums for the existing evolution components. + `PauliString` and `Hamiltonian` describe observables, and both can give expectation values; `Hamiltonian` can also be converted into an evolution circuit through Trotter decomposition, returning to the circuit space of `cqlib.circuit` for execution. --- diff --git a/docs/api/en/python/3_qis/10_fermion.md b/docs/api/en/python/3_qis/10_fermion.md new file mode 100644 index 00000000..9044bf9e --- /dev/null +++ b/docs/api/en/python/3_qis/10_fermion.md @@ -0,0 +1,70 @@ +# Fermionic Operators and Jordan–Wigner Mapping + +`cqlib.qis.fermion` exposes general fermionic algebra and sparse mappings backed by Rust Core. Public types are also exported from `cqlib.qis`. + +```python +from cqlib.qis import FermionicLadder, FermionicOp, JordanWignerMapper + +a = FermionicOp.annihilation(num_modes=4, mode=0) +assert (a * a.adjoint() + a.adjoint() * a).equiv(FermionicOp.identity(4)) +term = [FermionicLadder.create(2), FermionicLadder.annihilate(0)] +op = FermionicOp.from_term(num_modes=4, term=term, coefficient=0.5j) +hamiltonian = JordanWignerMapper().map_operator(op) +``` + +## Operators and Arithmetic + +`FermionicLadder.create(mode)` and `annihilate(mode)` construct immutable ladders with read-only `mode` and `kind`, `adjoint()`, value equality and hashing. The operator containing a ladder validates its mode against the declared mode space. + +`FermionicOp(num_modes)` constructs zero; `identity(num_modes)` constructs identity. `from_term(num_modes, term, coefficient=1.0)` accepts an ordered product. `from_terms(num_modes, terms)` accepts an iterable of `(term, coefficient)` tuples and merges duplicate products. An empty product is identity; an empty sum is zero. Both retain their declared mode count, including zero modes. + +| Interface | Behavior | +| --- | --- | +| `creation` / `annihilation` / `number` | Arguments are `num_modes, mode`; construct creation, annihilation or mode-number operators. | +| `total_number(num_modes)` | Construct total particle number. | +| `A + B` / `A - B` / `-A` | Return new operators; addition and subtraction require matching mode counts. | +| `A * B` | Operator product AB: B acts first, without implicit normal ordering. | +| `c * A` / `A * c` / `A.scaled(c)` | Scale by a finite integer, float or complex coefficient. | +| `adjoint()` | Conjugate coefficients, reverse products and exchange ladder kinds. | +| `normal_order()` | Return a new expansion: creators first, ascending modes within each group, including contractions and signs. | +| `add_term(term, coefficient=1.0)` | Mutate atomically and return `None`. | +| `chop(*, atol=0.0)` | Remove coefficients with complex magnitude <= tolerance in place; return `None`. | +| `equiv(other, *, atol=0.0)` | Compare algebraically after normal ordering; mismatched mode counts raise an error. | +| `is_hermitian(*, atol=0.0)` | Compare algebraically with the adjoint. | + +Read-only `num_modes` and `num_terms` describe storage. `terms` returns an independent snapshot of `(tuple[FermionicLadder, ...], complex)` pairs. Equality compares stored structure; `is_zero()` tests empty storage. Use `equiv()` for algebraic equality or zero. + +Only exact zeros are removed by default. Tolerances must be finite and nonnegative. `copy()` and Python copy protocols create independent objects. Operators are mutable and unhashable. `A += B` rebinds the result without modifying aliases of A. Use `sum(operators, start=FermionicOp(num_modes))` to sum operators. + +## Excitation Generators and Evolution + +`excitation_generator(num_modes, sources, targets)` constructs G = i(T − T†), with target creators in input order followed by source annihilators in reverse input order. Thus `[0, 1] -> [2, 3]` means T = a†₂ a†₃ a₁ a₀. Lists must be nonempty, equally sized, individually unique and disjoint. No implicit sorting or factorial normalization is applied. + +```python +from cqlib.circuit.ansatz import BasisEncoding, EvolutionStrategy, PauliEvolutionAnsatz + +mapper = JordanWignerMapper() +circuit = BasisEncoding(mapper.map_occupation([1, 1, 0, 0])).build_circuit("hf") +for name, sources, targets in [ + ("theta_double", [0, 1], [2, 3]), + ("theta_single", [0], [2]), +]: + generator = FermionicOp.excitation_generator(4, sources, targets) + block = (PauliEvolutionAnsatz(mapper.map_operator(generator)) + .with_strategy(EvolutionStrategy.exact()) + .with_time_param_name(name).build_circuit("excitation")) + circuit.compose(block) +bound = circuit.assign_parameters({"theta_double": 0.2, "theta_single": -0.3}) +``` + +Each block implements exp(−iθG) = exp(θ(T − T†)). Build and name separate blocks for independent parameters; evolving a sum of generators uses one shared parameter. + +## Mappings and Extension + +`JordanWignerMapper()` provides `map_operator(op) -> Hamiltonian`, `num_qubits(num_modes) -> int` and `map_occupation(occupation) -> list[bool]`. Operator mapping accepts non-Hermitian, identity and zero operators; downstream evolution and expectation consumers impose Hermiticity requirements. + +Mode p maps to qubit p, with a Z chain on lower-numbered modes. Qubit 0 is the least significant bit. Occupations must be integer zero/one or booleans; returned `bits[p]` addresses qubit p. Empty input returns an empty list. Core specifies no chemical or alpha/beta orbital ordering. + +`FermionToQubitMapper` and `OccupationStateMapper` are independent runtime-checkable `typing.Protocol` interfaces. Custom implementations need matching methods without inheriting a binding class. Runtime checks establish member presence only, not signatures or correctness. Algorithms call Python mappers directly; no automatic Rust trait callback bridge is provided. + +Wrong types raise `TypeError`; negative or out-of-range modes raise `IndexError`. Negative mode counts, mismatched spaces, nonfinite coefficients, invalid occupations or tolerances raise `ValueError`. Mode integers outside the Rust integer range raise `OverflowError`. diff --git a/docs/api/en/python/3_qis/1_statevector.md b/docs/api/en/python/3_qis/1_statevector.md index 3a31f359..691df57d 100644 --- a/docs/api/en/python/3_qis/1_statevector.md +++ b/docs/api/en/python/3_qis/1_statevector.md @@ -20,6 +20,8 @@ Amplitudes are stored contiguously by index in memory, and the amplitude of the ### Statevector(num_qubits) +Raises `ValueError` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + Create a state in |0…0⟩. Parameters: diff --git a/docs/api/en/python/3_qis/2_density_matrix.md b/docs/api/en/python/3_qis/2_density_matrix.md index c1d50ebe..7f9641a2 100644 --- a/docs/api/en/python/3_qis/2_density_matrix.md +++ b/docs/api/en/python/3_qis/2_density_matrix.md @@ -20,6 +20,8 @@ Data is stored contiguously in row-major order. Qubit i corresponds to bit i of ### DensityMatrix(num_qubits) +Raises `ValueError` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + Create a pure state in |0…0⟩⟨0…0|. Parameters: diff --git a/docs/api/en/python/3_qis/3_density_matrix_noise.md b/docs/api/en/python/3_qis/3_density_matrix_noise.md index a2983041..0de4d8f6 100644 --- a/docs/api/en/python/3_qis/3_density_matrix_noise.md +++ b/docs/api/en/python/3_qis/3_density_matrix_noise.md @@ -21,6 +21,8 @@ Data is stored contiguously in row-major order. Qubit i corresponds to bit i of ### DensityMatrixNoise(num_qubits, noise_model=None) +Raises `ValueError` if the state dimension is unrepresentable or state allocation fails. Zero-qubit states are supported. + Create a simulator. Omitting the noise model is equivalent to an ideal simulation. Parameters: @@ -169,7 +171,7 @@ All gate application and state rewriting methods modify the current state in pla **Probabilities** - `probabilities() -> list[float]`: return the probability of each basis state without readout noise, with length 2^num_qubits. Does not modify the state. -- `probabilities_with_readout(qubits) -> list[float]`: return the probability distribution after readout noise is applied on the given qubits, with length 2^n, where n is the length of `qubits`. +- `probabilities_with_readout(qubits) -> list[float]`: `qubits` contains storage positions on which to apply readout errors. Circuit-bound states look up noise using the circuit ID at each position; unbound states use identity IDs. Returns all `2^num_qubits` probabilities in storage order, independent of the selection order or size; an empty selection applies no readout errors. Out-of-range positions raise `IndexError` even without a noise model. - `qubits` (`list[int]`): the list of qubit indices taking part in readout noise modeling. An `IndexError` is raised when an index is out of range. **Measurement and sampling** diff --git a/docs/api/en/python/3_qis/7_hamiltonian.md b/docs/api/en/python/3_qis/7_hamiltonian.md index 9f27e7b2..9286c66c 100644 --- a/docs/api/en/python/3_qis/7_hamiltonian.md +++ b/docs/api/en/python/3_qis/7_hamiltonian.md @@ -99,6 +99,7 @@ Raises: - `to_trotter_circuit(time, steps, mode) -> Circuit`: generate the time evolution circuit given by the Trotter-Suzuki decomposition, approximating $U(t) = e^{-iHt}$ by a sequence of Pauli rotations. - `to_evolution_circuit(time, steps, mode) -> Circuit`: generate the time evolution circuit. When all terms commute, an exact single-pass decomposition is used; when non-commuting terms exist, it falls back to the specified Trotter mode and number of steps. - `copy() -> Hamiltonian`: return a copy. +- Standard-library `copy.copy(h)` and `copy.deepcopy(h)` also return independent copies of the terms. - `expectation_statevector(sv) -> float`: compute the expectation value from a statevector. - `expectation_density_matrix(dm) -> float`: compute the expectation value from a density matrix. - `expectation_probs(measurements) -> float`: compute the expectation value from measurement probabilities. @@ -113,6 +114,8 @@ Raises: ### Raises +Real expectation and variance methods require a Hermitian operator after Pauli phases and duplicate terms are merged. Original and merged coefficients must be finite; violations raise `ValueError`. Small nonzero coefficients are retained. + - `ValueError`: the two operators have inconsistent qubit counts (`+`, `+=`), the qubit count of a term is inconsistent with the operator (`from_list`, `add_term`), the coefficient type is not supported, the observable and the quantum state have inconsistent qubit counts (`expectation_*`, `variance_statevector`), or no usable measurement basis is found in the measurement probabilities (`expectation_probs`). - `ValueError`: `to_trotter_circuit` and `to_evolution_circuit` raise when `steps` is `0`, the operator is empty, a coefficient is not Hermitian, or a Pauli string phase is not Hermitian. @@ -220,3 +223,39 @@ assert trotterized.num_qubits == 1 | `ValueError` | `expectation_probs` cannot derive the target operator from the given measurement bases. | The input types of observable computation are given in [Statevector](1_statevector.md) and [DensityMatrix](2_density_matrix.md); the definition of Trotter modes is given in [Trotter evolution](8_evolution.md). + +## Validated Sparse Algebra + +`from_terms(num_qubits, terms)` declares the width explicitly and accepts `(PauliString, int/float/complex)` pairs. It validates widths and finite coefficients, absorbs Pauli phases and merges duplicates, removing only exact zeros. Empty input retains the declared width. + +| Interface | Behavior | +| --- | --- | +| `normalized()` | Return a validated, merged copy retaining every nonzero coefficient. | +| `add(other)` | Return a validated, merged sum on the same register. | +| `A - B`, `A * B`, `-A` | Checked subtraction, operator multiplication and negation; B acts first in AB. | +| `c * A`, `A * c`, `scaled(c)` | Validate the factor and resulting coefficients; return a new object. | +| `adjoint()` | Return the conjugate transpose, accounting for Pauli phases. | +| `chop(*, atol=0.0)` | Normalize and truncate by complex magnitude in place; errors preserve the object. | +| `equiv(other, *, atol=0.0)` | Compare normalized coefficient differences; width mismatch raises an error. Tolerance is not a matrix operator-norm bound. | +| `is_hermitian(*, atol=0.0)` | Compare with the adjoint: normalized coefficients satisfy 2*abs(imag) <= atol. | +| `normalized_hermitian()` | Project imaginary residuals <= 1e-10 to zero; reject larger ones and retain all nonzero real parts. | +| `tensor(other)` | Return self tensor other; other occupies low qubits. | +| `remap_qubits(mapping, target_width)` | Embed mapping[source] = destination; destinations must be unique and in range. Unused targets are identity. | + +General algebra accepts non-Hermitian operators. Evolution and expectation consumers enforce Hermiticity. Tolerances must be finite and nonnegative. Qubit embedding is not a fermionic mode permutation. + +```python +from cqlib.qis import Hamiltonian, PauliString + +x = Hamiltonian.from_terms(1, [(PauliString.from_str("X"), 1.0)]) +z = Hamiltonian.from_terms(1, [(PauliString.from_str("Z"), 1.0)]) +assert (x * z).equiv(Hamiltonian.from_terms(1, [(PauliString.from_str("Y"), -1j)])) +assert x.add(x).equiv(2 * x) +assert x.remap_qubits([2], target_width=3).num_qubits == 3 +``` + +### Legacy Compatibility + +`from_list`, `add_term`, `scale`, `+` and `+=` keep their existing behavior. Addition concatenates stored terms; `scale` mutates in place. Legacy `simplify()` truncates near-zero coefficients. Use `normalized()` to retain small mapped coefficients, or `chop(atol=...)` for explicit truncation. + +`add_term()` and `scale()` return `None` and do not support chaining. New algebra operations raise `ValueError` on mismatched widths, nonfinite coefficients or intermediate coefficient overflow. diff --git a/docs/api/en/python/3_qis/9_metrics_entropy.md b/docs/api/en/python/3_qis/9_metrics_entropy.md index d7cf7246..56c3be53 100644 --- a/docs/api/en/python/3_qis/9_metrics_entropy.md +++ b/docs/api/en/python/3_qis/9_metrics_entropy.md @@ -370,6 +370,8 @@ assert abs(entropy.linear_entropy(dm_pure) - 0.0) < 1e-10 ### `renyi_entropy(dm, alpha) -> float` +The order must be positive and not NaN. At `alpha = 1` the result is the von Neumann entropy; positive infinity returns min-entropy. Nearby orders use stable evaluation. Non-diagonal spectra treat eigenvalues at or below `dimension × f64::EPSILON × largest eigenvalue` as numerical zeros; diagonal spectra retain all positive entries. + Compute the Rényi entropy of order `alpha`. Parameters: @@ -383,7 +385,7 @@ Returns: Raises: -- `ValueError`: `alpha` is not greater than zero, or eigendecomposition failure. +- `ValueError`: `alpha` is NaN or not greater than zero, or eigendecomposition failure. Example: diff --git a/docs/api/en/python/4_compile/6_decompose_resynthesis.md b/docs/api/en/python/4_compile/6_decompose_resynthesis.md index 7d07baec..f9cc255d 100644 --- a/docs/api/en/python/4_compile/6_decompose_resynthesis.md +++ b/docs/api/en/python/4_compile/6_decompose_resynthesis.md @@ -61,7 +61,7 @@ The circuit-level entry point is located in `cqlib.compile.transform.decompose`, ### decompose_unitaries(circuit, config=None) -Synthesize one-qubit and two-qubit unitary gates from matrices. +Synthesize matrix-backed gates with fixed numeric arguments. Gates on three or more qubits use Block-ZXZ before routing and target-basis conversion. Parameters: @@ -84,13 +84,14 @@ Returns: - `(TransformResult, DecompositionRuleStats)` -### UnitaryDecomposeConfig(*, two_qubit_basis=None, target_basis=None, recurse_control_flow=True) +### UnitaryDecomposeConfig(*, two_qubit_basis=None, target_basis=None, recurse_control_flow=True, block_zxz_options=None) Parameters: - `two_qubit_basis` (`TwoQubitUnitaryDecomposeBasis | None`): the two-qubit synthesis gate basis. - `target_basis` (`list[str | Instruction] | None`): the target gate set constraint; entries take the same form as `target_basis` in `compile()`. - `recurse_control_flow` (`bool`): whether to recurse into control flow blocks. +- `block_zxz_options` (`BlockZxzDecomposeOptions | None`): optimization switches applied to three-or-more-qubit Block-ZXZ synthesis; `None` selects `BlockZxzDecomposeOptions()`. `two_qubit_basis` and `target_basis` are mutually exclusive; providing both is rejected. @@ -99,6 +100,7 @@ Attributes: - `two_qubit_basis -> TwoQubitUnitaryDecomposeBasis | None` - `target_basis -> list[Instruction] | None` - `recurse_control_flow -> bool` +- `block_zxz_options -> BlockZxzDecomposeOptions` Raises: @@ -124,6 +126,40 @@ Rule cache statistics within the pass: --- +## Block-ZXZ synthesis + +```python +from cqlib.compile.transform.decompose import ( + BlockZxzDecomposeOptions, + decompose_block_zxz, + decompose_block_zxz_with_options, +) + +circuit = decompose_block_zxz(matrix, atol=1e-10) +options = BlockZxzDecomposeOptions(opt_a1=True, opt_a2=True, opt_a2_force=False) +circuit = decompose_block_zxz_with_options(matrix, atol=1e-10, options=options) +``` + +Both functions accept a finite unitary array of shape `(2**n, 2**n)` for +`n >= 1` and return a `Circuit` whose `to_matrix()` includes the original +global phase. Local qubit 0 is the least significant matrix bit. +`atol` is a finite nonnegative absolute tolerance that validates input unitarity +(`||M†M - I||_max <= atol`) and governs reconstruction of demultiplexers and two-qubit leaves; +near-unitary inputs passing validation are projected onto the nearest unitary `U_proj` (in every +unitarily invariant norm) when needed, and synthesis reconstructs `U_proj` within `atol`. Invalid matrix values, dimensions or tolerance raise +`CompilerConfigError`. Numerical synthesis failures raise `CompilerTransformError`. + +A.1 absorbs two boundary CX gates per recursive node. A.2 transfers a +diagonal remainder between two-qubit leaves. Both default on. A.2 is +disabled for block-diagonal inputs unless explicitly forced. +`BlockZxzDecomposeOptions.none()` disables both reductions. +For three or more qubits, exact block-diagonal inputs use a single multiplexer. +Equal halves leave the highest qubit idle. If a two-qubit KAK leaf cannot meet +the requested precision, synthesis checks an additional Block-ZXZ layer +against the original 4×4 matrix. +Generic three- and four-qubit cases can reach 19 and 95 CX respectively. +Numerical fallback can add gates and preserves the full matrix. + ## Numeric unitary synthesis `cqlib.compile.transform.decompose.unitary` provides direct synthesis from a matrix to a gate sequence, without circuit traversal. diff --git a/docs/api/en/python/5_visualization/3_state_plots.md b/docs/api/en/python/5_visualization/3_state_plots.md index 806f9aed..ccfcbf9c 100644 --- a/docs/api/en/python/5_visualization/3_state_plots.md +++ b/docs/api/en/python/5_visualization/3_state_plots.md @@ -120,6 +120,8 @@ Raises: Compute the expectation values of the quantum state in the Pauli basis and render them as a bar chart. +By default, labels follow `PauliString`: the highest-index qubit is on the left and qubit 0 is on the right. For example, `IX` measures X on qubit 0 of a two-qubit state. Enabling `reverse_bits` reverses the characters in each label without changing the corresponding expectation value. + Parameters: - `state` (`QuantumState`): the quantum state to render. diff --git a/docs/api/en/python/6_error_mitigation/0_overview.md b/docs/api/en/python/6_error_mitigation/0_overview.md index e44b6fa0..1ff01191 100644 --- a/docs/api/en/python/6_error_mitigation/0_overview.md +++ b/docs/api/en/python/6_error_mitigation/0_overview.md @@ -30,7 +30,7 @@ The unified pipeline selects the execution path by method: Neither method executes the input circuit directly; both first construct a family of mitigation circuits: - Zero-noise extrapolation expands the circuit according to the fold level. Global folding rewrites the circuit as `U -> U (U† U)^level`, so that the circuit depth grows with the level; selective folding performs the same expansion only on operations whose instruction name matches the given gate set, leaving the other operations as they are. When the level is `0` the mitigation circuit is a copy of the input circuit. -- Virtual distillation copies the circuit `copies` times and inserts SWAPs qubit-wise, yielding a copy-swap circuit of `copies` times the width. The numerator and the denominator are executed on the same circuit, differing only in the observable passed to the callback: the denominator is `None` and the numerator is the `Hamiltonian` expanded by the number of copies. +- Virtual distillation copies the circuit `copies` times, appends one ancillary qubit prepared in `|+⟩` by a Hadamard gate, and applies SWAPs between adjacent copies controlled by the ancillary qubit, yielding a copy-swap circuit of `copies` times the width plus 1. The numerator and the denominator are executed on the same circuit, differing only in the observable passed to the callback: the numerator receives the `Hamiltonian` expanded to the full width (the original observable on the first copy ⊗ `X` on the ancillary qubit), and the denominator receives the `Hamiltonian` with only `X` on the ancillary qubit. ### Data flow @@ -104,9 +104,9 @@ The call order is constrained by the object itself: each `ErrorMitigation` insta | **Selective folding** | Folding applied only to operations whose instruction name matches `gate_set`, leaving the other operations as they are. | | **Extrapolation method** | The fitting model that extrapolates expectation values at different noise factors to the zero-noise point, including the polynomial and exponential kinds. | | **Copies** | The number of copies of the density matrix in virtual distillation, given by `copies`, with a minimum of 2. | -| **copy-swap circuit** | The mitigation circuit obtained by copying the input circuit `copies` times and inserting SWAPs qubit-wise. | -| **Numerator circuit** | The copy-swap circuit execution used to estimate `Tr(O ρ^M)`, with the observable being the `Hamiltonian` expanded by the number of copies. | -| **Denominator circuit** | The copy-swap circuit execution used to estimate `Tr(ρ^M)`, with the observable being `None`. | +| **copy-swap circuit** | The mitigation circuit obtained by copying the input circuit `copies` times, appending one ancillary qubit prepared by a Hadamard gate, and applying ancilla-controlled SWAPs between adjacent copies qubit-wise. | +| **Numerator circuit** | The copy-swap circuit execution used to estimate `Tr(O ρ^M)`, with the observable being the `Hamiltonian` expanded to the full width (the original observable on the first copy ⊗ `X` on the ancillary qubit). | +| **Denominator circuit** | The copy-swap circuit execution used to estimate `Tr(ρ^M)`, with the observable being `X` on the ancillary qubit (identities elsewhere). | | **estimator** | The callback provided by the caller, which executes one mitigation circuit and returns an `(expectation value, variance)` pair. | | **Unified pipeline** | The sequential flow carried by `ErrorMitigation`: `run()` collects the estimates and `get_mitigated()` performs post-processing. | @@ -190,13 +190,20 @@ hamiltonian = Hamiltonian.from_list([(PauliString.from_str("Z"), 1.0)]) vd = VirtualDistillation(circuit, 2) copy_swap = vd.build_copy_swap_circuit() -print(copy_swap.width) # 2 +print(copy_swap.width) # 3 = copies * base_width + 1 def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) # 分母:Tr(ρ^M) - return (1.5, 0.25) # 分子:Tr(O ρ^M) + # 分子与分母都携带观测量:分子在第 0 份副本的比特上有非恒等 Pauli, + # 分母只有辅助比特(最后一个比特)上的 X + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) # 分子:Tr(O ρ^M) + return (2.0, 1.0) # 分母:Tr(ρ^M) expectation, variance = vd.run_vd( @@ -229,9 +236,14 @@ hamiltonian = Hamiltonian.from_list([(PauliString.from_str("Z"), 1.0)]) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) - return (1.5, 0.25) + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) + return (2.0, 1.0) mitigation = ErrorMitigation( diff --git a/docs/api/en/python/6_error_mitigation/2_virtual_distillation.md b/docs/api/en/python/6_error_mitigation/2_virtual_distillation.md index 2d5ca07f..ae0a8a04 100644 --- a/docs/api/en/python/6_error_mitigation/2_virtual_distillation.md +++ b/docs/api/en/python/6_error_mitigation/2_virtual_distillation.md @@ -2,7 +2,7 @@ `cqlib.error_mitigation.virtual_distillation` -`cqlib.error_mitigation.virtual_distillation` provides the low-level interface of virtual distillation: copy the base circuit several times and insert SWAPs to construct a copy-swap circuit, then estimate the numerator and the denominator separately, and finally compute the ratio to obtain the mitigated expectation value. This page covers `VirtualDistillation` and `VirtualDistillationConfig`. +`cqlib.error_mitigation.virtual_distillation` provides the low-level interface of virtual distillation: copy the base circuit several times, add one ancillary qubit prepared by a Hadamard gate and apply ancilla-controlled SWAPs between adjacent copies (a Hadamard-test circuit), then estimate the numerator and the denominator separately, and finally compute the ratio to obtain the mitigated expectation value. This page covers `VirtualDistillation` and `VirtualDistillationConfig`. ## Import @@ -50,7 +50,7 @@ Low-level helper class of virtual distillation; it holds a copy of the base circ Parameters: - `circuit` (`Circuit`): the base circuit. It is copied on construction and the circuit passed in is not modified. -- `copies` (`int`): the number of copies, which must not be less than 2, otherwise `ErrorMitigationError` is raised. The number of copies determines the width of the mitigation circuit: the width of the copy-swap circuit is `copies` times the width of the base circuit. +- `copies` (`int`): the number of copies, which must not be less than 2, otherwise `ErrorMitigationError` is raised. The number of copies determines the width of the mitigation circuit: the width of the copy-swap circuit is `copies` times the width of the base circuit plus 1 (the extra qubit is the ancillary qubit of the Hadamard test). ### Attributes @@ -59,7 +59,7 @@ Parameters: ### Methods - `set_copies(copies)`: update the number of copies. Validation is completed before assignment, so the number of copies of the object stays unchanged when validation fails. -- `build_copy_swap_circuit() -> Circuit`: construct the copy-swap circuit. The base circuit is first decomposed, then copied one by one into their respective qubit ranges, and finally SWAPs are inserted qubit-wise. +- `build_copy_swap_circuit() -> Circuit`: construct the copy-swap circuit. The base circuit is first decomposed, then copied one by one into their respective qubit ranges, and finally a Hadamard gate is applied to the trailing ancillary qubit, followed by SWAPs between adjacent copies controlled by the ancillary qubit. - `run_denominator_circuit(shots, estimator) -> tuple[float, float]`: execute the denominator circuit and return the pair given by the callback. - `run_numerator_circuit(hamiltonian, shots, estimator) -> tuple[float, float]`: execute the numerator circuit and return the pair given by the callback. - `run_vd(hamiltonian, shots_numerator, shots_denominator, estimator) -> tuple[float, float]`: execute the numerator and the denominator in turn and compute the ratio, returning `(mitigated expectation value, variance)`. @@ -78,9 +78,9 @@ The output of `build_copy_swap_circuit()` consists of three parts: 1. The base circuit is first decomposed, ensuring that a group of already expanded operations is copied. 2. The base circuit is copied `copies` times, with the `i`-th copy landing on the qubit range offset by `i` times the base width. -3. For the 1st copy and each of the other copies, SWAPs are inserted qubit-wise. SWAPs are inserted only between the 1st copy and each of the other copies; the other copies are not directly connected to one another. +3. One ancillary qubit is appended as the last qubit, prepared in `|+⟩` by an `H` gate; then, between each pair of adjacent copies, SWAPs are inserted qubit-wise, all controlled by the ancillary qubit (CSWAP). This ladder of controlled SWAPs implements the derangement of the copies required by the Hadamard test. -Therefore, when the number of copies is 2, each operation of the base circuit appears 2 times, plus the qubit-wise SWAPs; as the number of copies increases, the number of SWAPs grows linearly with the number of copies rather than as pairwise combinations of copies. +Therefore, when the number of copies is 2, each operation of the base circuit appears 2 times, plus one `H` on the ancillary qubit and the qubit-wise controlled SWAPs; as the number of copies increases, the number of controlled SWAPs grows linearly with the number of copies rather than as pairwise combinations of copies. ```python from cqlib.circuit import Circuit @@ -91,7 +91,7 @@ circuit.x(0) vd = VirtualDistillation(circuit, 2) copy_swap = vd.build_copy_swap_circuit() -print(copy_swap.width) # 2 +print(copy_swap.width) # 3 = copies * base_width + 1 ``` --- @@ -102,11 +102,13 @@ Virtual distillation has only one mitigation circuit; both the numerator and the | Method | Circuit received by the callback | Observable received by the callback | Shots received by the callback | | --- | --- | --- | --- | -| `run_denominator_circuit(shots, estimator)` | copy-swap circuit | `None` | `shots` | -| `run_numerator_circuit(hamiltonian, shots, estimator)` | copy-swap circuit | The `Hamiltonian` expanded by the number of copies | `shots` | +| `run_denominator_circuit(shots, estimator)` | copy-swap circuit | `Hamiltonian` of `X` on the ancillary qubit (identities elsewhere) | `shots` | +| `run_numerator_circuit(hamiltonian, shots, estimator)` | copy-swap circuit | The `Hamiltonian` expanded to the full width (`O` on the first copy ⊗ `X` on the ancillary qubit) | `shots` | | `run_vd(...)` | copy-swap circuit | Numerator first, then denominator, as above | `shots_numerator` and `shots_denominator` respectively | -The observable used by the numerator is obtained by expanding the `Hamiltonian` passed in: the original Pauli terms are kept on their respective qubits and the higher-order qubits are padded with `Z`, so that the observable qubit count matches the width of the copy-swap circuit. The expansion is performed inside the class, and the caller only needs to pass the observable acting on the base circuit. +Both the numerator and the denominator observables are concrete `Hamiltonian` objects; they are told apart by content — the numerator observable has non-identity Paulis on the first copy's qubits, while the denominator observable is non-identity only on the ancillary (last) qubit. + +The observable used by the numerator is obtained by expanding the `Hamiltonian` passed in: the original Pauli terms are kept on their respective qubits (the first copy), the remaining copies are padded with `I`, and an `X` is appended on the ancillary qubit, so that the observable qubit count matches the width of the copy-swap circuit. The expansion is performed inside the class, and the caller only needs to pass the observable acting on the base circuit. `run_vd()` completes two steps in turn: first execute the numerator with `shots_numerator`, then execute the denominator with `shots_denominator`, and then combine the results as follows: @@ -136,9 +138,16 @@ vd = VirtualDistillation(circuit, 2) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) # 分母:Tr(ρ^M) - return (1.5, 0.25) # 分子:Tr(O ρ^M) + # 分子与分母都携带观测量:分子在第 0 份副本的比特上有非恒等 Pauli, + # 分母只有辅助比特(最后一个比特)上的 X + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) # 分子:Tr(O ρ^M) + return (2.0, 1.0) # 分母:Tr(ρ^M) expectation, variance = vd.run_vd( diff --git a/docs/api/en/python/6_error_mitigation/3_unified.md b/docs/api/en/python/6_error_mitigation/3_unified.md index cfc15745..bbfba3ec 100644 --- a/docs/api/en/python/6_error_mitigation/3_unified.md +++ b/docs/api/en/python/6_error_mitigation/3_unified.md @@ -161,7 +161,7 @@ When the `RunArgs` passed to `run()` do not match the method given at constructi Zero-noise extrapolation: `run()` constructs the mitigation circuits according to the configured fold levels, calls the callback once per circuit, with the observable being the `Hamiltonian` passed in and the number of shots taken from `RunArgs.zne(shots=...)`. Only the 1st element of the pair returned by the callback is used, and the variance is discarded. `get_mitigated()` fits the extrapolation input, and the `variance` of the result is `None`. -Virtual distillation: `run()` first constructs the copy-swap circuit, then calls the callback twice on the same circuit — the numerator first, then the denominator. The numerator receives the observable expanded by the number of copies and `shots_numerator`, and the denominator receives `None` and `shots_denominator`. `get_mitigated()` computes the ratio according to the combination formula of [Virtual distillation](2_virtual_distillation.md), and the `variance` of the result has a value. +Virtual distillation: `run()` first constructs the copy-swap circuit, then calls the callback twice on the same circuit — the numerator first, then the denominator. The numerator receives the observable expanded to the full width (the original observable on the first copy ⊗ `X` on the ancillary qubit) and `shots_numerator`, and the denominator receives the observable with only `X` on the ancillary qubit and `shots_denominator`. `get_mitigated()` computes the ratio according to the combination formula of [Virtual distillation](2_virtual_distillation.md), and the `variance` of the result has a value. ### Example diff --git a/docs/api/en/rust/0_circuit/4_operation_instruction.md b/docs/api/en/rust/0_circuit/4_operation_instruction.md index b76256c2..2a8df7a4 100644 --- a/docs/api/en/rust/0_circuit/4_operation_instruction.md +++ b/docs/api/en/rust/0_circuit/4_operation_instruction.md @@ -98,11 +98,25 @@ Category checks use a set of constant predicates, all evaluated at compile time: | `is_delay()` | Whether the instruction is a delay instruction. | | `is_quantum_gate()` | Whether the instruction is a unitary quantum gate, that is, one of the first four categories. | -### 3. Structural equality +### 3. Payload accessors + +Each category predicate is paired with a payload accessor that returns the wrapped definition, so callers can dispatch on `is_*()` and then read the payload without pattern matching. Every accessor returns `None` when the variant does not match. + +| Method | Returns | Description | +| --- | --- | --- | +| `standard_gate()` | `Option` | The standard gate definition when the instruction is a standard gate. | +| `mc_gate()` | `Option<&MCGate>` | The multi-controlled gate definition when the instruction is an mc-gate instruction. | +| `unitary_gate()` | `Option<&UnitaryGate>` | The user-defined unitary gate definition when the instruction is a unitary instruction. | +| `circuit_gate()` | `Option<&CircuitGate>` | The composite gate definition when the instruction is a circuit-gate instruction. | +| `directive()` | `Option` | The directive when the instruction is a non-unitary instruction. | +| `classical_data()` | `Option<&ClassicalDataOp>` | The classical data operation when the instruction is a classical data operation. | +| `classical_control()` | `Option<&ClassicalControlOp>` | The storage-layer control flow operation when the instruction is structured control flow. | + +### 4. Structural equality `Instruction` implements `PartialEq`. Two instructions are equal if and only if their variants and internal definitions agree structurally; the comparison does not involve qubit binding or parameter values. -### 4. Common methods +### 5. Common methods | Method | Description | | --- | --- | @@ -113,7 +127,7 @@ Category checks use a set of constant predicates, all evaluated at compile time: | `inverse(params)` | Try to return the inverse instruction and inverse parameters; non-invertible instructions return `None`. | | `control(num_new_ctrls)` | Try to promote the current instruction to a controlled instruction. | -### 5. `From` conversions +### 6. `From` conversions `Instruction` supports conversion from several underlying types, which makes it convenient to create instructions quickly when building IR or in compiler passes. @@ -277,7 +291,10 @@ The common methods are as follows: | `is_standard()` / `is_mcgate()` / `is_unitary()` / `is_circuit_gate()` | Determine whether the instruction is a standard gate, a multi-controlled gate, a custom unitary gate or a composite gate respectively. | | `is_directive()` / `is_classical_data()` / `is_delay()` | Determine whether the instruction is a non-unitary instruction, a classical data operation or a delay instruction respectively. | | `standard_gate()` | Return the corresponding `StandardGate` when the instruction is a standard gate. | +| `mc_gate()` / `unitary_gate()` / `circuit_gate()` | Return a reference to the corresponding gate definition when the instruction is of the matching category. | | `directive()` | Return the corresponding `Directive` when the instruction is a non-unitary instruction. | +| `classical_data()` | Return a reference to the `ClassicalDataOp` when the instruction is a classical data operation. | +| `classical_control()` | Return a reference to the `ValueClassicalControlOp` when the instruction is construction-layer control flow. | | `as_instruction()` | Read a reference to the inner `Instruction`. | | `into_instruction()` | Consume the object and take out the inner `Instruction`. | diff --git a/docs/api/en/rust/1_ir/3_qasm3.md b/docs/api/en/rust/1_ir/3_qasm3.md index 8bc15b95..858f89a5 100644 --- a/docs/api/en/rust/1_ir/3_qasm3.md +++ b/docs/api/en/rust/1_ir/3_qasm3.md @@ -99,6 +99,7 @@ The following OpenQASM 3.0 features are not supported in the current implementat - Subroutines and external calls: `def` subroutines, `extern` - Hardware-related: hardware qubits, `output` declarations, and `input` declarations other than angle and float - Other statements: `alias`, `pragma`, annotations, legacy declarations +- Program termination: `end` is explicitly rejected in every scope, including unreachable branches and zero-iteration loops - Gate modifiers: `negctrl`, `pow`; `ctrl` and `inv` are available only when a corresponding implementation exists for the target gate - Some standard gates: `ch`, `cp`, `cu`, `cswap` - Control flow: a lowering path for `while` exists in the implementation, but a loop with a runtime condition is currently rejected by the semantic check; `for` supports only the statically expanded form with a constant range diff --git a/docs/api/en/rust/3_qis/1_statevector.md b/docs/api/en/rust/3_qis/1_statevector.md index bc6a0a7a..42a89a49 100644 --- a/docs/api/en/rust/3_qis/1_statevector.md +++ b/docs/api/en/rust/3_qis/1_statevector.md @@ -32,7 +32,10 @@ Methods: ### Construction and amplitude access +`new` panic when the dimension is unrepresentable or state allocation fails. Use the corresponding `try_*` constructor to handle these errors. Zero-qubit states are supported. + - `fn new(num_qubits: usize) -> Self`: construct the `|0...0>` state with the first component set to 1 and the rest 0. +- `fn try_new(num_qubits: usize) -> Result`: construct the ground state, returning `QisError::InvalidParameterValue` for an unrepresentable dimension or `QisError::UnsupportedOperation` when state allocation fails. - `fn from_state(num_qubits: usize, initial_state: Vec) -> Result`: construct from the given amplitudes; the length must equal `2^num_qubits` and the state must already be normalized. - `fn data(&self) -> &[Complex64]`: read all amplitudes as a shared slice. - `fn data_mut(&mut self) -> &mut [Complex64]`: read all amplitudes as a mutable slice; modification may break normalization. diff --git a/docs/api/en/rust/3_qis/2_density_matrix.md b/docs/api/en/rust/3_qis/2_density_matrix.md index 8a1a4602..22bb4467 100644 --- a/docs/api/en/rust/3_qis/2_density_matrix.md +++ b/docs/api/en/rust/3_qis/2_density_matrix.md @@ -32,9 +32,14 @@ Methods: ### Construction and data access +`new`, `zeros` and `maximally_mixed` panic when the dimension is unrepresentable or state allocation fails. Use the corresponding `try_*` constructor to handle these errors. Zero-qubit states are supported. + - `fn new(num_qubits: usize) -> Self`: construct the pure state `|0...0><0...0|`. +- `fn try_new(num_qubits: usize) -> Result`: construct the ground state, returning `QisError::InvalidParameterValue` for an unrepresentable dimension or `QisError::UnsupportedOperation` when state allocation fails. - `fn maximally_mixed(num_qubits: usize) -> Self`: construct the maximally mixed state `I / 2^N`, where every computational basis state is equally probable and there are no coherence terms. +- `fn try_maximally_mixed(num_qubits: usize) -> Result`: fallible variant with the same errors as `try_new`. - `fn zeros(num_qubits: usize) -> Self`: construct an all-zero matrix; it is not a valid physical state (trace 0) and is used as the accumulation starting point for operations such as quantum channels. +- `fn try_zeros(num_qubits: usize) -> Result`: fallible variant with the same errors as `try_new`. - `fn from_state(num_qubits: usize, initial_state: Vec) -> Result`: construct by the outer product of pure state amplitudes `ρ = |ψ><ψ|`. - `fn from_density_matrix_state(num_qubits: usize, dm_state: Vec) -> Result`: construct directly from a flattened `2^N × 2^N` matrix, validating Hermiticity, positive semidefiniteness and unit trace. - `fn data(&self) -> &[Complex64]`: read the flattened matrix elements as a shared slice. diff --git a/docs/api/en/rust/3_qis/3_density_matrix_noise.md b/docs/api/en/rust/3_qis/3_density_matrix_noise.md index aade08d4..a00c7174 100644 --- a/docs/api/en/rust/3_qis/3_density_matrix_noise.md +++ b/docs/api/en/rust/3_qis/3_density_matrix_noise.md @@ -35,7 +35,10 @@ Methods: ### Construction and circuit integration +`new` panic when the dimension is unrepresentable or state allocation fails. Use the corresponding `try_*` constructor to handle these errors. Zero-qubit states are supported. + - `fn new(num_qubits: usize, noise_model: Option) -> Self`: construct from a qubit count and a noise model; the initial state is `|0...0><0...0|`. +- `fn try_new(num_qubits: usize, noise_model: Option) -> Result`: construct the ground state, returning `QisError::InvalidParameterValue` for an unrepresentable dimension or `QisError::UnsupportedOperation` when state allocation fails. - `fn from_circuit(circuit: &Circuit, noise_model: Option) -> Result`: execute a circuit and return the simulator; the circuit is first decomposed into basis gates, and noise is applied after every gate. - `fn apply_circuit(&mut self, circuit: &Circuit) -> Result<(), QisError>`: apply a circuit to the current simulator in place; noise is applied according to the configured model. @@ -84,7 +87,7 @@ Methods: The simulator expresses "noise on the quantum state" and "noise on readout" separately: the former acts on the density matrix itself, while the latter only changes the reported probability distribution. - `fn probabilities(&self) -> Vec`: return the diagonal entries of the density matrix, that is the measurement probability of each computational basis state. Includes gate noise already applied and excludes readout noise. -- `fn probabilities_with_readout(&self, qubits: &[usize]) -> Result, QisError>`: based on `probabilities`, apply readout noise to the qubits listed in `qubits`. +- `fn probabilities_with_readout(&self, qubits: &[usize]) -> Result, QisError>`: `qubits` contains storage positions on which to apply readout errors. Circuit-bound states look up noise using the circuit ID at each position; unbound states use identity IDs. Returns all `2^num_qubits` probabilities in storage order; an empty selection applies no readout errors. Out-of-range positions return `QisError::IndexOutOfBounds` even without a noise model. - `fn probs(&self, measurement: &Measurement) -> Result, QisError>`: return the marginal probability distribution selected by `Measurement`, excluding readout noise. - `fn probs_with_readout(&self, measurement: &Measurement) -> Result, QisError>`: based on `probs`, apply readout noise to `measurement.qubits()`. diff --git a/docs/api/en/rust/3_qis/7_hamiltonian.md b/docs/api/en/rust/3_qis/7_hamiltonian.md index a5f1ae93..89721379 100644 --- a/docs/api/en/rust/3_qis/7_hamiltonian.md +++ b/docs/api/en/rust/3_qis/7_hamiltonian.md @@ -1,11 +1,11 @@ # Hamiltonian and Observable -`cqlib_core::qis::hamiltonian` +`cqlib_core::qis::hamiltonian` `cqlib_core::qis::observable` -This page covers the observable `Hamiltonian`, formed by Pauli strings and complex coefficients, and the unified interface `Observable` trait for computing expectation values. +This page covers the operator `Hamiltonian`, formed by Pauli strings and complex coefficients, and the unified `Observable` trait for computing real expectation values. -`Hamiltonian` is a sparse representation of a $2^N \times 2^N$ matrix, of the form $H = \sum_k c_k P_k$, where $c_k$ is a complex coefficient and $P_k$ is an $N$-qubit Pauli string. The same structure serves both as the Hamiltonian of a physical interpretation and as an arbitrary observable whose expectation value is needed. +`Hamiltonian` is a sparse representation of a $2^N \times 2^N$ matrix, of the form $H = \sum_k c_k P_k$, where $c_k$ is a complex coefficient and $P_k$ is an $N$-qubit Pauli string. The type permits non-Hermitian operators; real expectation and unitary evolution methods additionally check Hermiticity. ## Import @@ -46,10 +46,59 @@ Fields: - `fn simplify(&mut self)`: simplify the term list. The operation has two steps: absorb the internal phase of each `PauliString` into the coefficient, normalizing all Pauli strings to `Phase::Plus`; then group by the X and Z component vectors and merge the coefficients of identical operators. Coefficients whose absolute value is smaller than $10^{-10}$ are discarded. - `fn scale(&mut self, factor: Complex64)`: multiply the coefficients of all terms by the same complex factor. +### Checked Pauli-sum algebra + +The fallible interfaces below validate register widths, X/Z bit-vector lengths, finite coefficients and coefficient products/accumulations. Returned operators have phases absorbed, terms sorted deterministically by Z then X vectors, duplicates merged and only exact zeros removed. They do not use the default pruning threshold of `simplify()`. + +| Interface | Meaning | +| --- | --- | +| `identity(num_qubits) -> Self` | Identity on the declared register; scalar one at zero qubits. | +| `from_terms(num_qubits, terms) -> Result` | Checked construction from an `IntoIterator` of `(PauliString, Complex64)`; empty input retains the declared width. | +| `try_add(&self, other: &Self)` / `try_sub(&self, other: &Self)` | Same-width addition/subtraction returning `Result`, without modifying inputs. | +| `try_mul(&self, other: &Self) -> Result` | Matrix product $AB$: the right operand acts first. Results may be non-Hermitian. | +| `scaled(&self, factor: Complex64) -> Result` | Returns a scaled operator; checks the factor even for zero input. | +| `adjoint(&self) -> Result` | Conjugates coefficients after phase normalization to obtain $A^\dagger$. | +| `normalized(&self) -> Result` | Validates, absorbs phases, merges terms and removes only exact zeros. | +| `chop(&mut self, atol: f64) -> Result<(), QisError>` | Merges first, then removes coefficients with complex magnitude `≤ atol`; leaves the original unchanged on failure. | +| `equiv(&self, other: &Self, atol: f64) -> Result` | Checks whether every normalized coefficient of $A-B$ has magnitude `≤ atol`. | +| `is_hermitian(&self, atol: f64) -> Result` | Equivalent to `equiv` against the adjoint; does not project coefficients to real values. | +| `tensor(&self, other: &Self) -> Result` | $A\otimes B$: B occupies low qubits, A high qubits. | +| `remap_qubits(&self, mapping: &[usize], target_width: usize) -> Result` | `mapping[source] = destination`; permutations and embeddings insert I at unused positions. | + +Tolerances must be finite and nonnegative. `equiv` uses a per-coefficient tolerance, not a matrix operator-norm bound. Different widths return `QubitMismatch`; registers are never implicitly expanded. `is_hermitian` measures $A-A^\dagger$, bounding twice the imaginary coefficient magnitude after normalization, as for `FermionicOp`. The existing `normalized_hermitian()` has a separate consumer contract: imaginary magnitudes up to `1e-10` are projected to real values, while every nonzero real coefficient is retained. + +`remap_qubits` requires a mapping of the source width with distinct destinations below `target_width`, including for zero/identity operators. It is not a fermionic mode permutation or a partial trace. Zero operators retain register widths. Sparse operations support more than 64 qubits; multiplication can still expand to the product of the input term counts. + +When a tensor product or embedding requires Pauli terms, widths beyond BitVec's representable length return `UnsupportedOperation` before its length assertion can panic. Zero operators require no bit vectors and can retain larger declared widths. + +```rust +use cqlib_core::qis::{Hamiltonian, QisError}; +use num_complex::Complex64; + +let x = Hamiltonian::from_pauli("X".parse()?); +let z = Hamiltonian::from_pauli("Z".parse()?); +let sum = x.try_add(&z)?; +assert!(sum.try_mul(&sum)?.equiv(&Hamiltonian::identity(1).scaled(2.0.into())?, 0.0)?); + +let xz = x.try_mul(&z)?; // XZ = -iY +let minus_i_y = Hamiltonian::from_terms(1, [("Y".parse()?, Complex64::new(0.0, -1.0))])?; +assert!(xz.equiv(&minus_i_y, 0.0)?); +assert!(!xz.is_hermitian(0.0)?); + +// [X,Z], and X ⊗ Z: the rightmost character is qubit zero. +let commutator = xz.try_sub(&z.try_mul(&x)?)?; +assert!(commutator.equiv(&minus_i_y.scaled(2.0.into())?, 0.0)?); +assert!(x.tensor(&z)?.equiv(&Hamiltonian::from_pauli("XZ".parse()?), 0.0)?); +assert!(x.remap_qubits(&[2], 3)?.equiv(&Hamiltonian::from_pauli("XII".parse()?), 0.0)?); +# Ok::<(), QisError>(()) +``` + +Legacy `Add`, `scale`, `simplify` and constructors retain their contracts; prefer the checked interfaces for new callers. `PartialEq` compares stored structure: operators with different term orders, duplicates or phase distributions may be algebraically equivalent but unequal. Use `equiv` for that comparison. + ### Queries and conversion - `fn all_terms_commute(&self) -> bool`: determine whether all Pauli terms commute pairwise. When true, $e^{-iHt}$ can be decomposed term by term into an exact evolution. -- `fn to_matrix(&self) -> Result, QisError>`: return a dense $2^N \times 2^N$ matrix. When the qubit count of any term is inconsistent with `num_qubits`, `QisError::QubitMismatch` is returned. An empty operator returns the zero matrix of the corresponding dimension. +- `fn to_matrix(&self) -> Result, QisError>`: validate and return a dense $2^N \times 2^N$ matrix. Empty operators produce the corresponding zero matrix; zero-qubit input produces a 1×1 matrix. Dimensions, element count and byte count are checked before allocation. Size overflow or reservation failure returns `UnsupportedOperation`; malformed terms and nonfinite coefficients (including matrix-entry accumulation overflow) return the corresponding errors. Requires $O(4^N)$ memory and is intended for small systems. - `fn to_trotter_circuit(&self, time: f64, steps: usize, mode: TrotterMode) -> Result`: see [Trotter Evolution](8_evolution.md). - `fn to_evolution_circuit(&self, time: f64, steps: usize, mode: TrotterMode) -> Result`: see [Trotter Evolution](8_evolution.md). @@ -175,6 +224,8 @@ pub trait Observable { - `fn variance_statevector(&self, sv: &Statevector) -> Result`: compute the pure-state variance $\text{Var}(O) = \langle O^2 \rangle - \langle O \rangle^2$. The default implementation in the trait returns `QisError::UnsupportedOperation`; an observable that supports variance computation must override this method. +Real expectation and variance methods validate Hermiticity after merging phases and repeated terms, without pruning small nonzero coefficients. Non-finite original or merged coefficients return `QisError::InvalidParameterValue`; non-Hermitian operators return `QisError::NotHermitian`. + ### Implementors | Type | Description | diff --git a/docs/api/en/rust/3_qis/8_evolution.md b/docs/api/en/rust/3_qis/8_evolution.md index b453802b..2b018d86 100644 --- a/docs/api/en/rust/3_qis/8_evolution.md +++ b/docs/api/en/rust/3_qis/8_evolution.md @@ -193,7 +193,7 @@ Both entry points accept the same parameters: - `steps` (`usize`): the number of Trotter steps $n$, which must be greater than 0. - `mode` (`TrotterMode`): the decomposition mode. -Both first copy the Hamiltonian and simplify it, then check the imaginary part of the coefficients: when the absolute value of the imaginary part exceeds $10^{-10}$, `QisError::NotHermitian` is returned, because only Hermitian operators can generate unitary evolution. +Both first copy the Hamiltonian, absorb Pauli phases and merge repeated terms without pruning small nonzero coefficients, then check the imaginary part of the coefficients: when the absolute value of the imaginary part exceeds $10^{-10}$, `QisError::NotHermitian` is returned, because only Hermitian operators can generate unitary evolution. ### `fn to_trotter_circuit(&self, time: f64, steps: usize, mode: TrotterMode) -> Result` diff --git a/docs/api/en/rust/3_qis/9_metrics_entropy.md b/docs/api/en/rust/3_qis/9_metrics_entropy.md index cda03779..9d59322a 100644 --- a/docs/api/en/rust/3_qis/9_metrics_entropy.md +++ b/docs/api/en/rust/3_qis/9_metrics_entropy.md @@ -1,6 +1,6 @@ # Metrics and Entropy -`cqlib_core::qis::metrics` +`cqlib_core::qis::metrics` `cqlib_core::qis::entropy` This page covers the metrics and information measures between quantum states. `metrics` collects purity, fidelity, trace distance, von Neumann entropy and partial transpose related quantities; `entropy` collects linear entropy, Rényi entropy, and the measures aimed at entanglement. The functions of both modules take a statevector or a density matrix as input and return `Result` (except `density_matrix_to_faer`). @@ -143,6 +143,8 @@ The linear entropy $S_L(\rho) = 1 - \text{Tr}(\rho^2)$. It is `0.0` for a pure s ### `renyi_entropy(dm: &DensityMatrix, alpha: f64) -> Result` +The order must be positive and not NaN. At `alpha = 1` the result is the von Neumann entropy; positive infinity returns min-entropy. Nearby orders use stable evaluation. Non-diagonal spectra treat eigenvalues at or below `dimension × f64::EPSILON × largest eigenvalue` as numerical zeros; diagonal spectra retain all positive entries. + The Rényi entropy $S_\alpha(\rho) = \frac{1}{1-\alpha}\log_2\left(\sum_i \lambda_i^\alpha\right)$, where $\lambda_i$ are the eigenvalues of the density matrix. When $\alpha$ is not greater than 0, `QisError::InvalidParameterValue` is returned; when the difference between $\alpha$ and 1 is smaller than `f64::EPSILON`, the von Neumann entropy is used instead, avoiding division by zero. The result is truncated to a non-negative value. Example: @@ -283,7 +285,7 @@ Convert a density matrix into the matrix type of the eigendecomposition library, | Error | When it occurs | | --- | --- | | `QisError::QubitMismatch` | The two states involved in the operation have inconsistent qubit counts. | -| `QisError::InvalidParameterValue` | `alpha` of `renyi_entropy()` is not greater than 0. | +| `QisError::InvalidParameterValue` | `alpha` of `renyi_entropy()` is NaN or not greater than 0. | | `QisError::InvalidSubsystem` | The subsystem of `entanglement_entropy_pure()` is empty, contains all qubits, or has duplicate indices. | | `QisError::IndexOutOfBounds` | A target index of `partial_transpose()` is out of range, or a subsystem index of `entanglement_entropy_pure()` is out of range. | | `QisError::UnsupportedDimension` | The input of `concurrence()` and `entanglement_of_formation()` is not two-qubit. | diff --git a/docs/api/en/rust/4_compile/6_decompose_resynthesis.md b/docs/api/en/rust/4_compile/6_decompose_resynthesis.md index 18ba15dc..a1a63495 100644 --- a/docs/api/en/rust/4_compile/6_decompose_resynthesis.md +++ b/docs/api/en/rust/4_compile/6_decompose_resynthesis.md @@ -47,12 +47,19 @@ The circuit-level entry points are in `cqlib_core::compile::transform::decompose - `decompose_unitaries_with_rule_stats(circuit: &Circuit, config: UnitaryDecomposeConfig) -> Result<(TransformOutcome, DecompositionRuleStats), CompilerError>` - `DecomposeUnitaries`: a `Transformer` adapter with the configuration bound at construction time, constructed with `DecomposeUnitaries::new(config)`; implements `Default`. +For matrices acting on three or more qubits, the pass uses Block-ZXZ and emits +standard gates before routing and target-basis conversion. The first gate +argument is the most significant matrix bit. The cached rule stores the +numeric phase together with the operations. A conditional body receives its +own phase when that rule is applied inside control flow. + ### UnitaryDecomposeConfig ```rust pub struct UnitaryDecomposeConfig { pub two_qubit_target: TwoQubitSynthesisTarget, pub recurse_control_flow: bool, + pub block_zxz_options: BlockZxzDecomposeOptions, } ``` @@ -60,8 +67,9 @@ Fields: - `two_qubit_target`: the target capabilities used by exact two-qubit numeric synthesis, constructed with `TwoQubitSynthesisTarget::from_instructions(target_basis: Option<&[Instruction]>)`; `None` means no target constraint, enabling the neutral Pauli rotation fallback. - `recurse_control_flow`: whether to recurse into control flow blocks. +- `block_zxz_options`: optimization switches applied to three-or-more-qubit Block-ZXZ synthesis (`BlockZxzDecomposeOptions::default()` enables A.1 and A.2 with automatic block-diagonal handling). -Implements `Default`, equivalent to no target constraint with recursion into control flow blocks. +Implements `Default`, equivalent to no target constraint, recursion into control flow blocks, and default Block-ZXZ options. ### DecompositionRuleStats @@ -77,6 +85,28 @@ In-pass rule cache statistics: hits, misses and insert counts. --- +## Block-ZXZ synthesis + +The module `cqlib_core::compile::transform::decompose` re-exports +`decompose_block_zxz(matrix, atol)` and +`decompose_block_zxz_with_options(matrix, atol, &options)`. Both accept +`&Array2` and return `Result`. Supply a +finite square unitary of dimension `2^n` with `n >= 1`. Local qubit 0 is +the least significant bit. The circuit matrix includes the input's global +phase. The finite nonnegative absolute tolerance validates input unitarity (`||M†M - I||_max <= atol`) +and governs reconstruction checks for demultiplexers and two-qubit leaves; near-unitary inputs +passing validation are projected onto the nearest unitary `U_proj` (in every unitarily invariant +norm) when needed, and synthesis reconstructs `U_proj` within `atol`. + +`BlockZxzDecomposeOptions::default()` enables `opt_a1` (absorb boundary CX +gates) and `opt_a2` (transfer a diagonal between two-qubit leaves). +`opt_a2_force` permits A.2 on block-diagonal inputs when A.2 is enabled. +For three or more qubits, exact block-diagonal inputs use a single multiplexer. +Equal halves leave the highest qubit idle. If a two-qubit KAK leaf cannot meet +the requested precision, synthesis checks an additional Block-ZXZ layer +against the original 4×4 matrix. +Numerical fallback may emit an explicit diagonal and additional gates. + ## Numeric unitary gate synthesis `cqlib_core::compile::transform::decompose::unitary` provides direct synthesis from a matrix to a gate sequence, without circuit traversal. diff --git a/docs/api/en/rust/5_visualization/3_state_plots.md b/docs/api/en/rust/5_visualization/3_state_plots.md index 6181fb22..b199bc6d 100644 --- a/docs/api/en/rust/5_visualization/3_state_plots.md +++ b/docs/api/en/rust/5_visualization/3_state_plots.md @@ -118,6 +118,8 @@ assert!(svg.contains("Re[rho]")); Draw Pauli basis expectation values as a bar chart. The labels are tensor products of `I`, `X`, `Y` and `Z`, `4^n` of them in total, where `n` is the number of qubits. Non-negative bars and negative bars use different colors. +By default, labels follow `PauliString`: the highest-index qubit is on the left and qubit 0 is on the right. For example, `IX` measures X on qubit 0 of a two-qubit state. Enabling `reverse_bits` reverses the characters in each label without changing the corresponding expectation value. + Parameters: - `state` (`&S`, `S: StateVisualizationSource + ?Sized`): the input state. diff --git a/docs/api/en/rust/6_error_mitigation/0_overview.md b/docs/api/en/rust/6_error_mitigation/0_overview.md index 053dabe8..700e830f 100644 --- a/docs/api/en/rust/6_error_mitigation/0_overview.md +++ b/docs/api/en/rust/6_error_mitigation/0_overview.md @@ -24,7 +24,7 @@ This module does not include a simulation or execution backend; all mitigation m pub type Estimator<'a> = dyn Fn(&Circuit, Option<&Hamiltonian>, Option) -> (f64, f64) + 'a; ``` -The parameters are, in order, the circuit to execute, the observable to estimate and the number of shots, and the return value is `(expectation value, variance)`. A denominator circuit carries no observable, so the second parameter is `None`; `ZNEMitigation::run_em_sequence` does not specify a number of shots, so the third parameter is `None`. Public methods uniformly accept it as `&Estimator<'_>`, that is, the trait object reference `&dyn Fn(&Circuit, Option<&Hamiltonian>, Option) -> (f64, f64)`, and both closures and function items can be passed by reference directly. Only virtual distillation uses the variance in the return value; zero-noise extrapolation takes only the expectation value. +The parameters are, in order, the circuit to execute, the observable to estimate and the number of shots, and the return value is `(expectation value, variance)`. Virtual distillation passes a concrete observable for both the numerator and the denominator — the denominator observable is `X` on the ancillary qubit of the copy-swap circuit; `ZNEMitigation::run_em_sequence` does not specify a number of shots, so the third parameter is `None`. Public methods uniformly accept it as `&Estimator<'_>`, that is, the trait object reference `&dyn Fn(&Circuit, Option<&Hamiltonian>, Option) -> (f64, f64)`, and both closures and function items can be passed by reference directly. Only virtual distillation uses the variance in the return value; zero-noise extrapolation takes only the expectation value. ### Mitigation pipeline state @@ -100,8 +100,8 @@ assert_eq!(mitigated.expectation, 0.5); | **Gate folding** | A construction that rewrites a circuit as `U -> U (U† U)^level`; folding only the specified gates is called selective folding. | | **Virtual distillation** | A method that estimates `Tr(O ρ^M) / Tr(ρ^M)` through copies and a copy-swap circuit, where `M` is the number of copies. | | **Copy** | The number of copies of the base circuit prepared in parallel in virtual distillation; the minimum is 2. | -| **copy-swap circuit** | A circuit that places multiple copies of the base circuit side by side on non-overlapping qubit ranges and inserts a bitwise SWAP between the first copy and each of the others; its width equals the number of copies multiplied by the width of the base circuit. | -| **Numerator circuit / denominator circuit** | The two statistics circuits of virtual distillation. The numerator circuit carries the expanded observable; the denominator circuit carries no observable, and the estimator receives `None`. | +| **copy-swap circuit** | A circuit that places multiple copies of the base circuit side by side on non-overlapping qubit ranges, prepares one trailing ancillary qubit in `|+⟩` with a Hadamard gate, and applies a ladder of bitwise SWAPs between adjacent copies, all controlled by the ancillary qubit; its width equals the number of copies multiplied by the width of the base circuit, plus one. | +| **Numerator circuit / denominator circuit** | The two statistics circuits of virtual distillation. The numerator circuit carries the expanded observable (the original observable on the first copy and `X` on the ancillary qubit); the denominator circuit carries `X` on the ancillary qubit with identities elsewhere. | | **Mitigation pipeline** | The sequential flow represented by `ErrorMitigation`: `new` creates it, `run` collects the raw data, and `get_mitigated` performs the method-specific post-processing. | --- @@ -159,7 +159,8 @@ let mut mitigation = ErrorMitigation::new( ) .unwrap(); -// 分子线路带可观测量,分母线路不带 +// 分子与分母都携带可观测量:分子在第 0 份副本的比特上有非恒等 Pauli, +// 分母只有辅助比特上的 X mitigation .run( &hamiltonian, @@ -168,7 +169,12 @@ mitigation shots_denominator: 2, }, &|_circuit, hamiltonian_arg, shots| { - if hamiltonian_arg.is_some() { + let observable = hamiltonian_arg.unwrap(); + let is_numerator = observable + .terms + .iter() + .any(|(term, _)| term.get_pauli(0) != Pauli::I); + if is_numerator { assert_eq!(shots, Some(3)); (1.5, 0.25) } else { @@ -232,13 +238,18 @@ let hamiltonian = Hamiltonian::from_list(vec![(pauli, Complex64::new(1.0, 0.0))] let vd = VirtualDistillation::new(Circuit::new(1), 2).unwrap(); -// 两份基底线路加一对逐比特 SWAP +// 两份基底线路加 1 个辅助比特:辅助比特上的 H 与一次受控 SWAP let copy_swap = vd.build_copy_swap_circuit().unwrap(); -assert_eq!(copy_swap.width(), 2); +assert_eq!(copy_swap.width(), 3); let (mu_vd, var_vd) = vd .run_vd(&hamiltonian, 3, 2, &|_circuit, hamiltonian_arg, shots| { - if hamiltonian_arg.is_some() { + let observable = hamiltonian_arg.unwrap(); + let is_numerator = observable + .terms + .iter() + .any(|(term, _)| term.get_pauli(0) != Pauli::I); + if is_numerator { assert_eq!(shots, Some(3)); (1.5, 0.25) } else { diff --git a/docs/api/en/rust/6_error_mitigation/2_virtual_distillation.md b/docs/api/en/rust/6_error_mitigation/2_virtual_distillation.md index 182d5c90..24881f94 100644 --- a/docs/api/en/rust/6_error_mitigation/2_virtual_distillation.md +++ b/docs/api/en/rust/6_error_mitigation/2_virtual_distillation.md @@ -32,7 +32,7 @@ Other methods: - `fn new(circuit: Circuit, copies: usize) -> Result`: the creation entry point; it takes ownership of the circuit. The template circuit can only be passed through `new`, and there is no corresponding read interface. - `fn set_copies(&mut self, copies: usize) -> Result<(), ErrorMitigationError>`: updates the number of copies. On failure the original value stays unchanged. - `fn build_copy_swap_circuit(&self) -> Result`: constructs the copy-swap circuit from the base circuit. -- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), CircuitError>`: runs the denominator circuit and returns `(mean, variance)`. +- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`: runs the denominator circuit and returns `(mean, variance)`. - `fn run_numerator_circuit(&self, hamiltonian: &Hamiltonian, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`: runs the numerator circuit and returns `(mean, variance)`. - `fn run_vd(&self, hamiltonian: &Hamiltonian, shots_numerator: usize, shots_denominator: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`: runs the complete flow and returns the mitigated `(expectation value, variance)`. @@ -55,10 +55,10 @@ Raises: ### `build_copy_swap_circuit(&self) -> Result` -Constructs the copy-swap circuit, which consists of three parts: first the base circuit is decomposed into gates, then `copies` copies of the base circuit are prepared side by side — the `i`-th copy is shifted as a whole onto the qubit range starting at `i × base width`, and the copies do not overlap — and finally a `SWAP` is inserted bit by bit between the first copy and each of the others. +Constructs the copy-swap circuit — the Hadamard-test circuit of the virtual distillation protocol — which consists of three parts: first the base circuit is decomposed into gates, then `copies` copies of the base circuit are prepared side by side — the `i`-th copy is shifted as a whole onto the qubit range starting at `i × base width`, and the copies do not overlap — and finally one ancillary qubit (the last qubit) is prepared in `|+⟩` by a Hadamard gate, followed by a ladder of `SWAP`s between adjacent copies, each controlled by the ancillary qubit (CSWAP), implementing the derangement of the copies. -- The circuit width is `copies × base width`, where the base width is the width of the decomposed circuit. -- The number of operations is `copies` sets of base operations plus `(copies - 1) × base width` `SWAP`s. +- The circuit width is `copies × base width + 1`, where the base width is the width of the decomposed circuit and the last qubit is the ancillary qubit. +- The number of operations is `copies` sets of base operations plus one `H` and `(copies - 1) × base width` controlled `SWAP`s. Returns: @@ -70,8 +70,8 @@ Raises: ### Numerator and denominator -- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), CircuitError>`: estimates the denominator `Tr(ρ^M)` on the copy-swap circuit. The observable parameter the estimator receives is `None` and the number of shots is `Some(shots)`; for the callback form see [Overview](0_overview.md). -- `fn run_numerator_circuit(&self, hamiltonian: &Hamiltonian, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`: estimates the numerator `Tr(O ρ^M)` on the copy-swap circuit. The observable is first expanded inside the module to the width of the copy-swap circuit: the original Pauli terms keep their original qubit indices, phase and coefficients unchanged, and `Z` is filled in on the newly added higher-index qubits; the expanded result is passed in through the observable parameter of the estimator, and the number of shots is `Some(shots)`. +- `fn run_denominator_circuit(&self, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`: estimates the denominator `Tr(ρ^M)` on the copy-swap circuit. The estimator receives `Some(denominator observable)` — `X` on the ancillary qubit (the last qubit) with identities everywhere else — and the number of shots is `Some(shots)`; for the callback form see [Overview](0_overview.md). +- `fn run_numerator_circuit(&self, hamiltonian: &Hamiltonian, shots: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`: estimates the numerator `Tr(O ρ^M)` on the copy-swap circuit. The observable is first expanded inside the module to the width of the copy-swap circuit: the original Pauli terms keep their original qubit indices (i.e. they act on the first copy), phase and coefficients unchanged, the remaining copies are padded with `I`, and an `X` is appended on the ancillary qubit (the last qubit); the expanded result is passed in through the observable parameter of the estimator, and the number of shots is `Some(shots)`. - `fn run_vd(&self, hamiltonian: &Hamiltonian, shots_numerator: usize, shots_denominator: usize, estimator: &Estimator<'_>) -> Result<(f64, f64), ErrorMitigationError>`: first validates that the number of qubits of the Hamiltonian equals the width of the base circuit, then executes the numerator circuit and the denominator circuit in turn, and finally combines them into the mitigated result. The numerator and the denominator use their own number of shots. Raises for `run_vd`: @@ -94,11 +94,12 @@ let q0 = Qubit::new(0); let mut circuit = Circuit::new(1); circuit.x(q0).unwrap(); -// 两份单比特副本:X 作用于比特 0、X 作用于比特 1,再加一对逐比特 SWAP +// 两份单比特副本加 1 个辅助比特:X 作用于比特 0、X 作用于比特 1, +// 辅助比特(比特 2)上的 H,以及一次由辅助比特控制的 SWAP let vd = VirtualDistillation::new(circuit, 2).unwrap(); let copy_swap = vd.build_copy_swap_circuit().unwrap(); -assert_eq!(copy_swap.width(), 2); -assert_eq!(copy_swap.operations().len(), 3); +assert_eq!(copy_swap.width(), 3); +assert_eq!(copy_swap.operations().len(), 4); ``` ```rust @@ -127,11 +128,17 @@ let mut pauli = PauliString::new(1); pauli.set_pauli(0, Pauli::Z); let hamiltonian = Hamiltonian::from_list(vec![(pauli, Complex64::new(1.0, 0.0))]).unwrap(); -// 分子线路带可观测量,分母线路不带;两者使用各自的 shot 数 +// 分子与分母都携带可观测量,按内容区分:分子在第 0 份副本的比特上有 +// 非恒等 Pauli,分母只有辅助比特上的 X;两者使用各自的 shot 数 let vd = VirtualDistillation::new(Circuit::new(1), 2).unwrap(); let (mu_vd, var_vd) = vd .run_vd(&hamiltonian, 3, 2, &|_circuit, hamiltonian_arg, shots| { - if hamiltonian_arg.is_some() { + let observable = hamiltonian_arg.unwrap(); + let is_numerator = observable + .terms + .iter() + .any(|(term, _)| term.get_pauli(0) != Pauli::I); + if is_numerator { assert_eq!(shots, Some(3)); (1.5, 0.25) } else { @@ -175,6 +182,6 @@ There is no `Default` implementation, so `copies` must be given explicitly. Impl | `ErrorMitigationError::HamiltonianQubitCountMismatch` | The number of qubits of the Hamiltonian received by `run_vd` is inconsistent with the width of the base circuit. | | `ErrorMitigationError::ZeroDenominatorMean` | The mean of the denominator circuit is zero. | | `ErrorMitigationError::Circuit` | Carries `CircuitError::QubitCountMismatch`, indicating that the width of the expanded observable is inconsistent with the width of the copy-swap circuit. | -| `CircuitError` | The circuit error returned directly by `build_copy_swap_circuit` and `run_denominator_circuit`. | +| `CircuitError` | The circuit error returned directly by `build_copy_swap_circuit`; `run_denominator_circuit` wraps it into `ErrorMitigationError::Circuit`. | For the complete definition of the error type, see [Unified pipeline](3_unified.md). diff --git a/docs/api/en/rust/6_error_mitigation/3_unified.md b/docs/api/en/rust/6_error_mitigation/3_unified.md index 67c4d340..99ac0ab4 100644 --- a/docs/api/en/rust/6_error_mitigation/3_unified.md +++ b/docs/api/en/rust/6_error_mitigation/3_unified.md @@ -77,7 +77,7 @@ Parameters: Execution details differ by method: - Zero-noise extrapolation: constructs the folded circuits according to the configured fold levels, calls the estimator one by one with the observable parameter `Some(hamiltonian)` and the number of shots `RunArgs::Zne::shots`, and takes only the expectation value from the return value. The folded circuits, the expectation values, the noise factors and the execution arguments are kept together. -- Virtual distillation: constructs the copy-swap circuit and expands the observable to the width of that circuit; the estimator of the numerator circuit receives `Some(expanded observable)` and `Some(shots_numerator)`, and the denominator circuit receives `None` and `Some(shots_denominator)`. The means and variances of the numerator and the denominator are kept together. +- Virtual distillation: constructs the copy-swap circuit and expands the observable to the width of that circuit; the estimator of the numerator circuit receives `Some(expanded observable)` — the original observable on the first copy together with `X` on the ancillary qubit — and `Some(shots_numerator)`, and the denominator circuit receives `Some(denominator observable)` — `X` on the ancillary qubit with identities elsewhere — and `Some(shots_denominator)`. The means and variances of the numerator and the denominator are kept together. Returns: diff --git a/docs/documentation/cn/0_get_started/1_installation.md b/docs/documentation/cn/0_get_started/1_installation.md index 22fa4837..513249d0 100644 --- a/docs/documentation/cn/0_get_started/1_installation.md +++ b/docs/documentation/cn/0_get_started/1_installation.md @@ -4,7 +4,7 @@ 在安装 Cqlib 之前,请确保您的计算机环境满足以下条件: -- Python 环境:支持 Python 3.10 – 3.14(建议使用 64 位版本); +- Python 环境:支持启用 GIL 的 CPython 3.11 – 3.15(建议使用 64 位版本); - 操作系统: - Linux - macOS diff --git a/docs/documentation/cn/0_get_started/2_quickstart.md b/docs/documentation/cn/0_get_started/2_quickstart.md index 8c7889ba..308b59fd 100644 --- a/docs/documentation/cn/0_get_started/2_quickstart.md +++ b/docs/documentation/cn/0_get_started/2_quickstart.md @@ -4,7 +4,7 @@ 在开始之前,请确保您的环境已准备就绪: -- Python 环境:支持 Python 3.10 – 3.14 +- Python 环境:支持启用 GIL 的 CPython 3.11 – 3.15 - 完成 Cqlib 安装与环境配置(安装方式见 “[Cqlib 安装与环境配置](../0_get_started/1_installation.md)”) --- diff --git a/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md b/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md index 320ab40a..f8b55275 100644 --- a/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md +++ b/docs/documentation/cn/1_cqlib/1_ir/3_qasm3.md @@ -261,6 +261,7 @@ Cqlib 的 QASM3 loader 支持部分可映射到当前 `Circuit` 的控制流: | `reset`、`barrier`、`gphase` | 支持 | | 自定义 gate | 支持可映射的 gate body | | calibration、pulse、extern、hardware qubit、alias | 当前不支持 | +| 程序终止 `end` | 任何作用域中出现时均明确拒绝,包括不可达分支和零次循环 | | 任意复杂 classical arithmetic | 当前不支持无损 lowering | | 复杂 lvalue slicing、多维索引 | 当前不支持或仅支持必要子集 | diff --git a/docs/documentation/cn/1_cqlib/5_visualization/7_state_visualization.md b/docs/documentation/cn/1_cqlib/5_visualization/7_state_visualization.md index 539b52ea..7d8c5452 100644 --- a/docs/documentation/cn/1_cqlib/5_visualization/7_state_visualization.md +++ b/docs/documentation/cn/1_cqlib/5_visualization/7_state_visualization.md @@ -242,7 +242,9 @@ plot_state_paulivec( ![Asymmetric Pauli vector with reversed bits](assets/asymmetric_paulivec_reverse_bits.png) -在多比特状态图中,先确认 basis label 和 Pauli string 的显示顺序,再解释相干项、对角权重或 Pauli 期望值。 +默认 Pauli vector 标签遵循 `PauliString`:最高位在左,qubit 0 在最右侧。因此,`IX` 表示 qubit 0 上的 X,`XI` 表示 qubit 1 上的 X。上面的对角态在默认图中给出 `IZ = 0.6`、`ZI = -0.6`。设置 `reverse_bits=True` 时,每个标签中的字符顺序反转,对应的系数不变。 + +早期版本的多比特 Pauli 标签方向与此相反,现已修正。此前用 `reverse_bits=True` 对齐公共 `PauliString` 约定的代码,现在应使用默认设置。单比特图不受影响。 --- diff --git a/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec.png b/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec.png index 59102fa9..8675c36b 100644 Binary files a/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec.png and b/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec.png differ diff --git a/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png b/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png index 7168b937..b2e9be6f 100644 Binary files a/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png and b/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png differ diff --git a/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png b/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png index 7c4af68a..5878ed4a 100644 Binary files a/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png and b/docs/documentation/cn/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png differ diff --git a/docs/documentation/cn/1_cqlib/6_error_mitigation/0_overview.md b/docs/documentation/cn/1_cqlib/6_error_mitigation/0_overview.md index 2a8aae16..5f679932 100644 --- a/docs/documentation/cn/1_cqlib/6_error_mitigation/0_overview.md +++ b/docs/documentation/cn/1_cqlib/6_error_mitigation/0_overview.md @@ -88,7 +88,7 @@ Estimator = Callable[ | 参数 | 含义 | |------|------| | `run_circuit` | 待执行的线路(可能是折叠线路或 copy-swap 线路) | -| `observable` | 待估计的 `Hamiltonian`;分母线路时为 `None` | +| `observable` | 待估计的 `Hamiltonian`;VD 的分子与分母调用都会携带(分母观测量为辅助比特上的 `X`) | | `shots` | 本次执行的 shot 数;部分 API 可为 `None` | | 返回值 | `(expectation, variance)` | diff --git a/docs/documentation/cn/1_cqlib/6_error_mitigation/2_virtual_distillation.md b/docs/documentation/cn/1_cqlib/6_error_mitigation/2_virtual_distillation.md index 9544d1e8..55ec311f 100644 --- a/docs/documentation/cn/1_cqlib/6_error_mitigation/2_virtual_distillation.md +++ b/docs/documentation/cn/1_cqlib/6_error_mitigation/2_virtual_distillation.md @@ -1,6 +1,6 @@ # 虚拟蒸馏(Virtual Distillation) -虚拟蒸馏(Virtual Distillation, VD)通过多份密度矩阵拷贝与 **copy-swap** 线路,估计: +虚拟蒸馏(Virtual Distillation, VD)通过多份密度矩阵拷贝与 **copy-swap** 线路(即 Huggins 等人 PRX 11, 041036 的 Hadamard-test 线路),估计: ```text Tr(O ρ^M) / Tr(ρ^M) @@ -29,12 +29,19 @@ hamiltonian = Hamiltonian.from_list([(PauliString.from_str("Z"), 1.0)]) vd = em.VirtualDistillation(circuit, copies=2) copy_swap = vd.build_copy_swap_circuit() -print(copy_swap.width) # 2 +print(copy_swap.width) # 3 = copies * 基础宽度 + 1(最后一个比特是辅助比特) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) # denominator: Tr(ρ^M) - return (1.5, 0.25) # numerator: Tr(O ρ^M) + # 分子与分母都携带 Hamiltonian;分子在第 0 份副本的比特上有非恒等 + # Pauli,分母只在辅助比特(最后一个比特)上携带 X。 + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) # numerator: Tr(O ρ^M) + return (2.0, 1.0) # denominator: Tr(ρ^M) mean, var = vd.run_vd(hamiltonian, shots_numerator=3, shots_denominator=2, estimator=estimator) print("expectation:", mean) # 0.75 @@ -52,8 +59,8 @@ vd = em.VirtualDistillation(circuit, copies=2) copy_swap = vd.build_copy_swap_circuit() ``` -- 输出线路宽度为 `copies` × 基础线路宽度; -- 内部通过 pairwise `SWAP` 耦合各拷贝寄存器; +- 输出线路宽度为 `copies` × 基础线路宽度 **+ 1**,最后一个比特是辅助比特; +- 辅助比特先经 `H` 门制备到 `|+⟩`,然后在相邻副本之间施加**由辅助比特控制**的 `SWAP` 梯(CSWAP),实现各副本的轮换(derangement); - 原始 `circuit` 不会被修改。 可通过 `set_copies(copies)` 更新拷贝数,再重新构造线路。 @@ -64,11 +71,11 @@ copy_swap = vd.build_copy_swap_circuit() | API | 说明 | |-----|------| -| `run_denominator_circuit(shots, estimator)` | 估计 `Tr(ρ^M)`;`observable=None` | -| `run_numerator_circuit(hamiltonian, shots, estimator)` | 估计 `Tr(O ρ^M)` | +| `run_denominator_circuit(shots, estimator)` | 估计 `Tr(ρ^M)`;观测量为辅助比特上的 `X` | +| `run_numerator_circuit(hamiltonian, shots, estimator)` | 估计 `Tr(O ρ^M)`;观测量为第 0 份副本上的 `O` ⊗ 辅助比特上的 `X` | | `run_vd(hamiltonian, shots_numerator, shots_denominator, estimator)` | 一次完成分子/分母并返回比值 | -`estimator` 在分母调用时收到 `observable=None`,在分子调用时收到具体 `Hamiltonian`。 +`estimator` 在分子与分母调用中都收到具体 `Hamiltonian`:分子观测量在第 0 份副本的比特上非平凡,并在辅助比特上携带 `X`;分母观测量只在辅助比特上携带 `X`(其余为恒等)。 --- @@ -76,8 +83,8 @@ copy_swap = vd.build_copy_swap_circuit() | `copies` | 线路宽度 | 典型效果 | |----------|----------|----------| -| `2` | 2 比特 | 最低配置,开销较小 | -| `3` | 3 比特 | 更强蒸馏,开销更高 | +| `2` | 3 比特(2 份副本 + 1 个辅助比特) | 最低配置,开销较小 | +| `3` | 4 比特(3 份副本 + 1 个辅助比特) | 更强蒸馏,开销更高 | `M` 越大,越突出主导本征态成分,但制备与测量成本显著增加。 @@ -92,9 +99,14 @@ mitigation = em.ErrorMitigation( ) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) - return (1.5, 0.25) + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) + return (2.0, 1.0) mitigation.run(hamiltonian, em.RunArgs.virtual_distillation(3, 2), estimator) result = mitigation.get_mitigated(em.ProcessArgs.virtual_distillation()) @@ -110,7 +122,7 @@ VD 的 `MitigatedResult.variance` 通常有值。 ## 说明 - VD 适用于希望放大主导本征态、降低混合噪声影响的场景; -- `Hamiltonian` 会在内部按拷贝数扩展,无需手动复制 Pauli 项; +- 分子观测量会在内部扩展为「第 0 份副本上的 `O` ⊗ 其余副本恒等 ⊗ 辅助比特上的 `X`」,分母观测量为辅助比特上的 `X`,无需手动扩展 Pauli 项; - 正式实验应分别记录 numerator 与 denominator 的 shot 预算。 --- diff --git a/docs/documentation/cn/1_cqlib/6_error_mitigation/3_unified_api.md b/docs/documentation/cn/1_cqlib/6_error_mitigation/3_unified_api.md index 1da35aa8..f0e7872f 100644 --- a/docs/documentation/cn/1_cqlib/6_error_mitigation/3_unified_api.md +++ b/docs/documentation/cn/1_cqlib/6_error_mitigation/3_unified_api.md @@ -86,10 +86,15 @@ mitigation = em.ErrorMitigation( ) def estimator(run_circuit, observable, shots): - assert run_circuit.width == 2 - if observable is None: - return (2.0, 1.0) - return (1.5, 0.25) + assert run_circuit.width == 3 # 2 份副本 × 1 比特 + 1 个辅助比特 + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) + return (2.0, 1.0) mitigation.run(hamiltonian, em.RunArgs.virtual_distillation(3, 2), estimator) result = mitigation.get_mitigated(em.ProcessArgs.virtual_distillation()) @@ -137,7 +142,8 @@ em.MitigationMethod.virtual_distillation(em.VirtualDistillationConfig(2)) ```python def estimator(run_circuit, observable, shots): # run_circuit: 可能是折叠线路或 copy-swap 线路 - # observable: Hamiltonian 或 None(VD 分母) + # observable: Hamiltonian(VD 的分子与分母都会携带;分母观测量为 + # 辅助比特上的 X) # shots: int 或 None return (expectation, variance) ``` @@ -146,7 +152,7 @@ def estimator(run_circuit, observable, shots): - 返回值必须是 `(float, float)`; - ZNE 的 `run_em_sequence_with_shots` 会把 `shots` 传给 estimator; -- VD 分母路径上 `observable is None`; +- VD 的分子与分母路径上 `observable` 都是 `Hamiltonian`,按内容区分——分子在第 0 份副本的比特上有非恒等 Pauli,分母只在辅助比特(最后一个比特)上携带 `X`; - estimator 内部异常会原样向上抛出。 --- diff --git a/docs/documentation/cn/1_cqlib/7_tianyan/0_overview.md b/docs/documentation/cn/1_cqlib/7_tianyan/0_overview.md index e342c80b..c9944c26 100644 --- a/docs/documentation/cn/1_cqlib/7_tianyan/0_overview.md +++ b/docs/documentation/cn/1_cqlib/7_tianyan/0_overview.md @@ -80,7 +80,7 @@ backend = platform.get_backend("tianyan-287") qcis = "H Q1\nM Q1" task = backend.run([qcis], shots=1000) -results = task.wait(timeout_secs=120.0, poll_interval_secs=5.0) +results = task.wait(timeout=120.0, poll_interval=5.0) result = results[0] print(result.task_id) @@ -124,8 +124,8 @@ classDiagram +shots +submitted_at +status() - +wait(timeout_secs, poll_interval_secs) - +wait_raw(timeout_secs, poll_interval_secs) + +wait(timeout, poll_interval) + +wait_raw(timeout, poll_interval) } class ExecutionResult { +task_id diff --git a/docs/documentation/cn/1_cqlib/7_tianyan/3_task_result.md b/docs/documentation/cn/1_cqlib/7_tianyan/3_task_result.md index d2bcf7ce..984e1fd8 100644 --- a/docs/documentation/cn/1_cqlib/7_tianyan/3_task_result.md +++ b/docs/documentation/cn/1_cqlib/7_tianyan/3_task_result.md @@ -92,8 +92,8 @@ for result in partial_results: ```python results = task.wait( - timeout_secs=120.0, - poll_interval_secs=5.0, + timeout=120.0, + poll_interval=5.0, ) for result in results: @@ -106,8 +106,8 @@ for result in results: | 参数 | 说明 | |---|---| -| `timeout_secs` | 最大等待秒数 | -| `poll_interval_secs` | 轮询间隔秒数,默认 `5.0` | +| `timeout` | 最大等待秒数 | +| `poll_interval` | 轮询间隔秒数,默认 `5.0` | `wait()` 在阻塞等待时会释放 Python GIL,因此不会阻塞其他 Python 线程运行。 @@ -117,8 +117,8 @@ for result in results: ```python raw_results = task.wait_raw( - timeout_secs=120.0, - poll_interval_secs=5.0, + timeout=120.0, + poll_interval=5.0, ) ``` @@ -180,7 +180,7 @@ print(len(task.task_ids)) # 120 | 现象 | 常见原因 | 处理方式 | |---|---|---| | 提交失败 | 后端不可用、QCIS 格式错误、API Key 无效或网络问题 | 检查 `backend.status`、QCIS 文本和认证状态 | -| `wait` 超时 | 队列等待时间长或任务未完成 | 增大 `timeout_secs`,或改用 `status()` 分批查询 | +| `wait` 超时 | 队列等待时间长或任务未完成 | 增大 `timeout`,或改用 `status()` 分批查询 | | 返回结果少于提交线路数 | 使用了 `status()`,它只返回已完成结果 | 使用 `wait()` 等待全部完成 | | counts 为空 | 平台结果尚未完成或解析失败 | 检查任务状态和原始错误信息 | | 概率和 counts 不一致 | 概率由 counts 归一化得到,矫正模式可能改变 counts | 对比 `wait()` 和 `wait_raw()` | diff --git a/docs/documentation/cn/1_cqlib/7_tianyan/4_qcis_ir_workflow.md b/docs/documentation/cn/1_cqlib/7_tianyan/4_qcis_ir_workflow.md index 5a7b1730..124c005e 100644 --- a/docs/documentation/cn/1_cqlib/7_tianyan/4_qcis_ir_workflow.md +++ b/docs/documentation/cn/1_cqlib/7_tianyan/4_qcis_ir_workflow.md @@ -52,7 +52,7 @@ platform = TianyanPlatform.login(os.environ["TIANYAN_API_KEY"]) backend = platform.get_backend("tianyan-287") task = backend.run([qcis_text], shots=1000) -results = task.wait(timeout_secs=120.0) +results = task.wait(timeout=120.0) print(results[0].counts) ``` diff --git a/docs/documentation/cn/1_cqlib/7_tianyan/5_readout_mitigation.md b/docs/documentation/cn/1_cqlib/7_tianyan/5_readout_mitigation.md index a356909d..e26cad86 100644 --- a/docs/documentation/cn/1_cqlib/7_tianyan/5_readout_mitigation.md +++ b/docs/documentation/cn/1_cqlib/7_tianyan/5_readout_mitigation.md @@ -63,7 +63,7 @@ task = backend.run_with_mode( ```python task = backend.run(["H Q1\nM Q1"], shots=1000) -results = task.wait(timeout_secs=120.0) +results = task.wait(timeout=120.0) ``` `auto` 模式会在满足条件时自动应用读取误差矫正。 @@ -74,14 +74,14 @@ results = task.wait(timeout_secs=120.0) ```python task = backend.run_raw(["H Q1\nM Q1"], shots=1000) -raw_results = task.wait(timeout_secs=120.0) +raw_results = task.wait(timeout=120.0) ``` 或者在已有任务上使用 `wait_raw`: ```python task = backend.run(["H Q1\nM Q1"], shots=1000) -raw_results = task.wait_raw(timeout_secs=120.0) +raw_results = task.wait_raw(timeout=120.0) ``` ## 5. 显式指定矫正模式 @@ -135,8 +135,8 @@ qcis = "H Q1\nM Q1" task = backend.run([qcis], shots=1000) -calibrated = task.wait(timeout_secs=120.0) -raw = task.wait_raw(timeout_secs=120.0) +calibrated = task.wait(timeout=120.0) +raw = task.wait_raw(timeout=120.0) print("矫正后:", calibrated[0].counts, calibrated[0].probabilities) print("原始值:", raw[0].counts, raw[0].probabilities) diff --git a/docs/documentation/en/0_get_started/1_installation.md b/docs/documentation/en/0_get_started/1_installation.md index 74a39b3a..a6c6c0d3 100644 --- a/docs/documentation/en/0_get_started/1_installation.md +++ b/docs/documentation/en/0_get_started/1_installation.md @@ -4,7 +4,7 @@ This guide covers the installation of Cqlib and the setup of a development envir Before installing Cqlib, ensure that the environment meets the following conditions: -- Python environment: Python 3.10 – 3.14 is supported (a 64-bit build is recommended); +- Python environment: CPython 3.11 – 3.15 with the GIL enabled is supported (a 64-bit build is recommended); - Operating system: - Linux - macOS diff --git a/docs/documentation/en/0_get_started/2_quickstart.md b/docs/documentation/en/0_get_started/2_quickstart.md index 8f3c04a8..437bca81 100644 --- a/docs/documentation/en/0_get_started/2_quickstart.md +++ b/docs/documentation/en/0_get_started/2_quickstart.md @@ -4,7 +4,7 @@ This guide builds a minimal working quantum circuit with Cqlib and completes an Before starting, ensure that the environment is ready: -- Python environment: Python 3.10 – 3.14 is supported +- Python environment: CPython 3.11 – 3.15 with the GIL enabled is supported - Cqlib is installed and the environment is configured (for installation, see "[Cqlib Installation and Environment Setup](../0_get_started/1_installation.md)") --- diff --git a/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md b/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md index 2e700c56..2f3f11bf 100644 --- a/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md +++ b/docs/documentation/en/1_cqlib/1_ir/3_qasm3.md @@ -261,6 +261,7 @@ Recommended principle: if a circuit is mainly used for cross-toolchain exchange, | `reset`, `barrier`, `gphase` | Supported | | Custom gate | Supported for a mappable gate body | | calibration, pulse, extern, hardware qubit, alias | Currently not supported | +| Program termination `end` | Explicitly rejected in every scope, including unreachable branches and zero-iteration loops | | Arbitrary complex classical arithmetic | Lossless lowering is currently not supported | | Complex lvalue slicing, multi-dimensional indexing | Currently not supported, or only the necessary subset is supported | diff --git a/docs/documentation/en/1_cqlib/5_visualization/7_state_visualization.md b/docs/documentation/en/1_cqlib/5_visualization/7_state_visualization.md index 6122d0a6..5307b0ba 100644 --- a/docs/documentation/en/1_cqlib/5_visualization/7_state_visualization.md +++ b/docs/documentation/en/1_cqlib/5_visualization/7_state_visualization.md @@ -242,7 +242,9 @@ Pauli vector after reversing the display order: ![Asymmetric Pauli vector with reversed bits](assets/asymmetric_paulivec_reverse_bits.png) -In multi-qubit state figures, confirm the display order of the basis labels and Pauli strings before interpreting coherence terms, diagonal weights or Pauli expectation values. +By default, Pauli-vector labels follow `PauliString`: the highest-index qubit is on the left and qubit 0 is on the right. Thus `IX` measures X on qubit 0 and `XI` measures X on qubit 1. For the diagonal state above, the default plot gives `IZ = 0.6` and `ZI = -0.6`. With `reverse_bits=True`, each label's characters are reversed while its coefficient stays the same. + +Earlier versions displayed multi-qubit Pauli labels in the opposite direction. This has been corrected; code that used `reverse_bits=True` to match the public `PauliString` convention should now use the default. Single-qubit plots are unaffected. --- diff --git a/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec.png b/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec.png index 59102fa9..8675c36b 100644 Binary files a/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec.png and b/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec.png differ diff --git a/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png b/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png index 7168b937..b2e9be6f 100644 Binary files a/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png and b/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_report.png differ diff --git a/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png b/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png index 7c4af68a..5878ed4a 100644 Binary files a/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png and b/docs/documentation/en/1_cqlib/5_visualization/assets/asymmetric_paulivec_reverse_bits.png differ diff --git a/docs/documentation/en/1_cqlib/6_error_mitigation/0_overview.md b/docs/documentation/en/1_cqlib/6_error_mitigation/0_overview.md index fa255ee4..bd382e4f 100644 --- a/docs/documentation/en/1_cqlib/6_error_mitigation/0_overview.md +++ b/docs/documentation/en/1_cqlib/6_error_mitigation/0_overview.md @@ -88,7 +88,7 @@ Estimator = Callable[ | Parameter | Meaning | |------|------| | `run_circuit` | The circuit to be executed (possibly a folded circuit or a copy-swap circuit) | -| `observable` | The `Hamiltonian` to be estimated; `None` for the denominator circuit | +| `observable` | The `Hamiltonian` to be estimated; both VD numerator and denominator calls carry one (the denominator observable is `X` on the ancillary qubit) | | `shots` | The shot count of this execution; may be `None` in some APIs | | Return value | `(expectation, variance)` | diff --git a/docs/documentation/en/1_cqlib/6_error_mitigation/2_virtual_distillation.md b/docs/documentation/en/1_cqlib/6_error_mitigation/2_virtual_distillation.md index 1d5b463c..74e10c28 100644 --- a/docs/documentation/en/1_cqlib/6_error_mitigation/2_virtual_distillation.md +++ b/docs/documentation/en/1_cqlib/6_error_mitigation/2_virtual_distillation.md @@ -1,6 +1,6 @@ # Virtual Distillation (VD) -Virtual distillation (VD) estimates the following through multiple copies of the density matrix and a **copy-swap** circuit: +Virtual distillation (VD) estimates the following through multiple copies of the density matrix and a **copy-swap** circuit (the Hadamard-test circuit of Huggins et al., PRX 11, 041036): ```text Tr(O ρ^M) / Tr(ρ^M) @@ -29,12 +29,20 @@ hamiltonian = Hamiltonian.from_list([(PauliString.from_str("Z"), 1.0)]) vd = em.VirtualDistillation(circuit, copies=2) copy_swap = vd.build_copy_swap_circuit() -print(copy_swap.width) # 2 +print(copy_swap.width) # 3 = copies * base_width + 1 (the last qubit is the ancilla) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) # denominator: Tr(ρ^M) - return (1.5, 0.25) # numerator: Tr(O ρ^M) + # Both the numerator and the denominator carry a Hamiltonian; the + # numerator also acts on the first copy's qubits, the denominator only + # carries X on the ancillary (last) qubit. + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) # numerator: Tr(O ρ^M) + return (2.0, 1.0) # denominator: Tr(ρ^M) mean, var = vd.run_vd(hamiltonian, shots_numerator=3, shots_denominator=2, estimator=estimator) print("expectation:", mean) # 0.75 @@ -52,8 +60,8 @@ vd = em.VirtualDistillation(circuit, copies=2) copy_swap = vd.build_copy_swap_circuit() ``` -- The output circuit width is `copies` × the base circuit width; -- The copy registers are coupled internally through pairwise `SWAP`; +- The output circuit width is `copies` × the base circuit width **+ 1**; the last qubit is an ancillary qubit; +- The ancillary qubit is first prepared in `|+⟩` by an `H` gate, then adjacent copies are coupled by a ladder of `SWAP`s, each **controlled by the ancillary qubit** (CSWAP), which implements the derangement of the copies; - The original `circuit` is not modified. The number of copies can be updated through `set_copies(copies)`, and the circuit can then be reconstructed. @@ -64,11 +72,11 @@ The number of copies can be updated through `set_copies(copies)`, and the circui | API | Description | |-----|------| -| `run_denominator_circuit(shots, estimator)` | Estimates `Tr(ρ^M)`; `observable=None` | -| `run_numerator_circuit(hamiltonian, shots, estimator)` | Estimates `Tr(O ρ^M)` | +| `run_denominator_circuit(shots, estimator)` | Estimates `Tr(ρ^M)`; the observable is `X` on the ancillary qubit | +| `run_numerator_circuit(hamiltonian, shots, estimator)` | Estimates `Tr(O ρ^M)`; the observable is `O` on the first copy ⊗ `X` on the ancillary qubit | | `run_vd(hamiltonian, shots_numerator, shots_denominator, estimator)` | Completes the numerator and denominator in one call and returns their ratio | -`estimator` receives `observable=None` in the denominator call and a concrete `Hamiltonian` in the numerator call. +`estimator` receives a concrete `Hamiltonian` in both calls: the numerator observable acts non-trivially on the first copy's qubits and carries `X` on the ancillary qubit, while the denominator observable carries only `X` on the ancillary qubit (identities elsewhere). --- @@ -76,8 +84,8 @@ The number of copies can be updated through `set_copies(copies)`, and the circui | `copies` | Circuit width | Typical effect | |----------|----------|----------| -| `2` | 2 qubits | Minimum configuration, lower overhead | -| `3` | 3 qubits | Stronger distillation, higher overhead | +| `2` | 3 qubits (2 copies + 1 ancilla) | Minimum configuration, lower overhead | +| `3` | 4 qubits (3 copies + 1 ancilla) | Stronger distillation, higher overhead | The larger `M` is, the more the dominant eigenstate component is emphasized, but the preparation and measurement cost increases significantly. @@ -92,9 +100,14 @@ mitigation = em.ErrorMitigation( ) def estimator(run_circuit, observable, shots): - if observable is None: - return (2.0, 1.0) - return (1.5, 0.25) + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) + return (2.0, 1.0) mitigation.run(hamiltonian, em.RunArgs.virtual_distillation(3, 2), estimator) result = mitigation.get_mitigated(em.ProcessArgs.virtual_distillation()) @@ -110,7 +123,7 @@ The `MitigatedResult.variance` of VD usually has a value. ## Notes - VD suits scenarios where the dominant eigenstate is to be amplified and the impact of mixed noise reduced; -- The `Hamiltonian` is expanded internally according to the number of copies, so Pauli terms do not need to be copied manually; +- The numerator observable is expanded internally to `O` on the first copy ⊗ identities ⊗ `X` on the ancillary qubit, and the denominator observable is `X` on the ancillary qubit, so Pauli terms do not need to be expanded manually; - Formal experiments should record the shot budget of the numerator and the denominator separately. --- diff --git a/docs/documentation/en/1_cqlib/6_error_mitigation/3_unified_api.md b/docs/documentation/en/1_cqlib/6_error_mitigation/3_unified_api.md index b370fd5d..6e15f0e5 100644 --- a/docs/documentation/en/1_cqlib/6_error_mitigation/3_unified_api.md +++ b/docs/documentation/en/1_cqlib/6_error_mitigation/3_unified_api.md @@ -70,10 +70,15 @@ mitigation = em.ErrorMitigation( ) def estimator(run_circuit, observable, shots): - assert run_circuit.width == 2 - if observable is None: - return (2.0, 1.0) - return (1.5, 0.25) + assert run_circuit.width == 3 # 2 copies × 1 qubit + 1 ancilla + is_numerator = any( + qubit < observable.num_qubits - 1 + for term, _ in observable.terms + for qubit in term.support() + ) + if is_numerator: + return (1.5, 0.25) + return (2.0, 1.0) mitigation.run(hamiltonian, em.RunArgs.virtual_distillation(3, 2), estimator) result = mitigation.get_mitigated(em.ProcessArgs.virtual_distillation()) @@ -121,7 +126,9 @@ em.MitigationMethod.virtual_distillation(em.VirtualDistillationConfig(2)) ```python def estimator(run_circuit, observable, shots): # run_circuit: may be a folded circuit or a copy-swap circuit - # observable: a Hamiltonian or None (VD denominator) + # observable: a Hamiltonian (for VD both the numerator and the + # denominator carry one; the denominator observable is X + # on the ancillary qubit) # shots: an int or None return (expectation, variance) ``` @@ -130,7 +137,7 @@ Confirm the following when implementing: - The return value must be `(float, float)`; - The `run_em_sequence_with_shots` of ZNE passes `shots` to the estimator; -- On the VD denominator path, `observable is None`; +- On both VD paths `observable` is a `Hamiltonian`; the numerator and denominator are told apart by content — the numerator acts non-trivially on the first copy's qubits, the denominator carries only `X` on the ancillary (last) qubit; - Exceptions inside the estimator are propagated upwards as-is. --- diff --git a/docs/documentation/en/1_cqlib/7_tianyan/0_overview.md b/docs/documentation/en/1_cqlib/7_tianyan/0_overview.md index c19564a4..613466ad 100644 --- a/docs/documentation/en/1_cqlib/7_tianyan/0_overview.md +++ b/docs/documentation/en/1_cqlib/7_tianyan/0_overview.md @@ -80,7 +80,7 @@ backend = platform.get_backend("tianyan-287") qcis = "H Q1\nM Q1" task = backend.run([qcis], shots=1000) -results = task.wait(timeout_secs=120.0, poll_interval_secs=5.0) +results = task.wait(timeout=120.0, poll_interval=5.0) result = results[0] print(result.task_id) @@ -124,8 +124,8 @@ classDiagram +shots +submitted_at +status() - +wait(timeout_secs, poll_interval_secs) - +wait_raw(timeout_secs, poll_interval_secs) + +wait(timeout, poll_interval) + +wait_raw(timeout, poll_interval) } class ExecutionResult { +task_id diff --git a/docs/documentation/en/1_cqlib/7_tianyan/3_task_result.md b/docs/documentation/en/1_cqlib/7_tianyan/3_task_result.md index c7caa3ae..72a76a47 100644 --- a/docs/documentation/en/1_cqlib/7_tianyan/3_task_result.md +++ b/docs/documentation/en/1_cqlib/7_tianyan/3_task_result.md @@ -92,8 +92,8 @@ Suitable for implementing polling logic manually, or for refreshing task status ```python results = task.wait( - timeout_secs=120.0, - poll_interval_secs=5.0, + timeout=120.0, + poll_interval=5.0, ) for result in results: @@ -106,8 +106,8 @@ Parameter description: | Parameter | Description | |---|---| -| `timeout_secs` | Maximum number of seconds to wait | -| `poll_interval_secs` | Polling interval in seconds, default `5.0` | +| `timeout` | Maximum number of seconds to wait | +| `poll_interval` | Polling interval in seconds, default `5.0` | `wait()` releases the Python GIL while blocking, so it does not block other Python threads from running. @@ -117,8 +117,8 @@ By default, `wait()` decides whether to apply readout error correction according ```python raw_results = task.wait_raw( - timeout_secs=120.0, - poll_interval_secs=5.0, + timeout=120.0, + poll_interval=5.0, ) ``` @@ -180,7 +180,7 @@ It is recommended to check the following before submission: | Symptom | Common cause | Handling | |---|---|---| | Submission fails | Backend unavailable, QCIS format error, invalid API Key or network problem | Check `backend.status`, the QCIS text and the authentication status | -| `wait` times out | Long queue wait time or the task has not completed | Increase `timeout_secs`, or use `status()` to query in batches | +| `wait` times out | Long queue wait time or the task has not completed | Increase `timeout`, or use `status()` to query in batches | | Fewer results returned than submitted circuits | `status()` was used, which returns only completed results | Use `wait()` to wait for all of them to complete | | counts is empty | The platform result has not completed or parsing failed | Check the task status and the raw error message | | Probabilities and counts are inconsistent | Probabilities are normalized from counts, and the correction mode may change counts | Compare `wait()` with `wait_raw()` | diff --git a/docs/documentation/en/1_cqlib/7_tianyan/4_qcis_ir_workflow.md b/docs/documentation/en/1_cqlib/7_tianyan/4_qcis_ir_workflow.md index 7a9eb06a..af112903 100644 --- a/docs/documentation/en/1_cqlib/7_tianyan/4_qcis_ir_workflow.md +++ b/docs/documentation/en/1_cqlib/7_tianyan/4_qcis_ir_workflow.md @@ -52,7 +52,7 @@ platform = TianyanPlatform.login(os.environ["TIANYAN_API_KEY"]) backend = platform.get_backend("tianyan-287") task = backend.run([qcis_text], shots=1000) -results = task.wait(timeout_secs=120.0) +results = task.wait(timeout=120.0) print(results[0].counts) ``` diff --git a/docs/documentation/en/1_cqlib/7_tianyan/5_readout_mitigation.md b/docs/documentation/en/1_cqlib/7_tianyan/5_readout_mitigation.md index 157308d0..9a03aaff 100644 --- a/docs/documentation/en/1_cqlib/7_tianyan/5_readout_mitigation.md +++ b/docs/documentation/en/1_cqlib/7_tianyan/5_readout_mitigation.md @@ -63,7 +63,7 @@ task = backend.run_with_mode( ```python task = backend.run(["H Q1\nM Q1"], shots=1000) -results = task.wait(timeout_secs=120.0) +results = task.wait(timeout=120.0) ``` The `auto` mode applies readout error correction automatically when the conditions are met. @@ -74,14 +74,14 @@ To obtain raw counts only without any correction, use `run_raw`: ```python task = backend.run_raw(["H Q1\nM Q1"], shots=1000) -raw_results = task.wait(timeout_secs=120.0) +raw_results = task.wait(timeout=120.0) ``` Or use `wait_raw` on an existing task: ```python task = backend.run(["H Q1\nM Q1"], shots=1000) -raw_results = task.wait_raw(timeout_secs=120.0) +raw_results = task.wait_raw(timeout=120.0) ``` ## 5. Specifying the correction mode explicitly @@ -135,8 +135,8 @@ qcis = "H Q1\nM Q1" task = backend.run([qcis], shots=1000) -calibrated = task.wait(timeout_secs=120.0) -raw = task.wait_raw(timeout_secs=120.0) +calibrated = task.wait(timeout=120.0) +raw = task.wait_raw(timeout=120.0) print("corrected:", calibrated[0].counts, calibrated[0].probabilities) print("raw:", raw[0].counts, raw[0].probabilities) diff --git a/docs/releasing.md b/docs/releasing.md index bf40e612..7c12acca 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -2,9 +2,8 @@ ## File Organization -The structure follows Qiskit's separation of entry-point workflows, reusable -workflows, and tools scripts, without adopting its automated publishing steps -or modifying project source code, existing tests, or Cargo configuration. +CQLib separates entry-point workflows, reusable workflows, and tool scripts. +Publishing is triggered manually through release tags. | File | Responsibility | | --- | --- | @@ -40,16 +39,35 @@ Tags use the Python version to identify a release batch: - Stable releases: `vX.Y.Z`. - Prereleases: `vX.Y.Z-alpha.N`, `vX.Y.Z-beta.N`, or `vX.Y.Z-rc.N`, with N starting at 1. -- Current tag: `v1.4.0-beta.1`. -- Current Python source version: `1.4.0-beta1`, normalized to `1.4.0b1` for PEP 440 and wheel filenames. -- Current Rust/C version: `0.1.0-beta.1`; both inherit the workspace version. +- Planned release tag: `v2.0.0-beta.7` (create manually after validation). +- Current Python source version: `2.0.0-beta7`, normalized to `2.0.0b7` for PEP 440 and wheel filenames. +- Current Rust/C version: `0.1.0-beta.7`; both inherit the workspace version. Python and Rust/C versions evolve independently and do not need matching numbers. The Cargo.toml files at a given tag record the version mapping for that release; no separate release.toml is maintained. CI checks that the tag is equivalent to the Python version, core dependency -versions are consistent across bindings, the minimum Python version is 3.10, -and `abi3-py310` is enabled. Maintainers must update versions before tagging. +versions are consistent across bindings, the minimum Python version is 3.11, +and `abi3-py311` is enabled. Maintainers must update versions before tagging. + +## Beta 6 Compatibility Notes + +Beta 6 fixes composite-gate parameter binding and qubit ordering, nested global +phase preservation, symbolic parameter substitution, density-matrix target +validation, readout-noise qubit lookup, NumPy complex Hamiltonian coefficients, +and Pauli-vector labels. Callers upgrading from beta 5 should account for: + +- `GPhase` matrices now have shape 1×1, consistent with a zero-qubit gate. +- Gate-local instruction and operation matrices put the first qubit argument + at the most-significant bit, including circuit-backed gates. Full circuit + matrices retain their least-significant-bit-first basis. +- Parameter substitution is simultaneous: replacement expressions are not + substituted again by other entries in the same binding map. +- Pauli-vector labels put qubit 0 at the right by default, matching `PauliString`. +- Readout-noise selections use storage positions; circuit-bound states resolve + the configured noise using the circuit qubit ID at each selected position. +- Density-matrix gate operations reject duplicate targets before changing the + state. ## Platforms and Artifacts @@ -70,8 +88,8 @@ Images use the latest tag, with the resolved digest recorded in logs. On macOS, CI checks the shared library's minimum deployment version. Tests actually run on macOS 15; this does not constitute execution testing on macOS 11. -Each platform produces one `cp310-abi3` wheel. That same wheel is installed into -separate CPython 3.10, 3.11, 3.12, 3.13, and 3.14 environments for import checks, +Each platform produces one `cp311-abi3` wheel. That same wheel is installed into +separate CPython 3.11, 3.12, 3.13, 3.14, and 3.15 environments for import checks, pip check, and the full pytest suite. Tests are copied alongside the installed package to satisfy existing sibling-directory assertions. They do not import cqlib from the checkout, and existing tests are not modified, skipped, or marked diff --git a/docs/whitepaper/Cqlib.pdf b/docs/whitepaper/Cqlib.pdf new file mode 100644 index 00000000..4ead2dbf Binary files /dev/null and b/docs/whitepaper/Cqlib.pdf differ diff --git a/tools/c-sdk/CMakeLists.txt b/tools/c-sdk/CMakeLists.txt index befa07af..3461149d 100644 --- a/tools/c-sdk/CMakeLists.txt +++ b/tools/c-sdk/CMakeLists.txt @@ -28,30 +28,33 @@ else() endif() foreach(kind static shared) - add_executable(test_${kind} test_circuit.c) - target_include_directories(test_${kind} PRIVATE "${CQLIB_SDK_ROOT}/include") - target_link_libraries(test_${kind} PRIVATE cqlib_${kind}) - # The C tests put API calls inside assert(); retain them even in Release. - if(MSVC) - target_compile_options(test_${kind} PRIVATE /UNDEBUG) - else() - target_compile_options(test_${kind} PRIVATE -UNDEBUG) - endif() - if(WIN32) - target_link_libraries(test_${kind} PRIVATE - ntdll ws2_32 bcrypt userenv advapi32) - elseif(APPLE) - target_link_libraries(test_${kind} PRIVATE c++ "-framework CoreFoundation") - else() - target_link_libraries(test_${kind} PRIVATE pthread dl m) - endif() - set_target_properties(test_${kind} PROPERTIES - BUILD_RPATH "${CQLIB_SDK_ROOT}/lib") - add_test(NAME c_${kind} COMMAND test_${kind}) + foreach(suite circuit qis_algebra density_matrix_targets) + set(test_target test_${suite}_${kind}) + add_executable(${test_target} test_${suite}.c) + set_target_properties(${test_target} PROPERTIES C_STANDARD 11 C_STANDARD_REQUIRED YES) + target_include_directories(${test_target} PRIVATE "${CQLIB_SDK_ROOT}/include") + target_link_libraries(${test_target} PRIVATE cqlib_${kind}) + # The C tests put API calls inside assert(); retain them even in Release. + if(MSVC) + target_compile_options(${test_target} PRIVATE /UNDEBUG) + else() + target_compile_options(${test_target} PRIVATE -UNDEBUG) + endif() + if(WIN32) + target_link_libraries(${test_target} PRIVATE + ntdll ws2_32 bcrypt userenv advapi32) + elseif(APPLE) + target_link_libraries(${test_target} PRIVATE c++ "-framework CoreFoundation") + else() + target_link_libraries(${test_target} PRIVATE pthread dl m) + endif() + set_target_properties(${test_target} PROPERTIES + BUILD_RPATH "${CQLIB_SDK_ROOT}/lib") + add_test(NAME c_${suite}_${kind} COMMAND ${test_target}) + if(WIN32 AND kind STREQUAL "shared") + add_custom_command(TARGET ${test_target} POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy_if_different + "$" "$") + endif() + endforeach() endforeach() - -if(WIN32) - add_custom_command(TARGET test_shared POST_BUILD - COMMAND ${CMAKE_COMMAND} -E copy_if_different - "$" "$") -endif() diff --git a/tools/c-sdk/README.md b/tools/c-sdk/README.md index 0ea4b178..64fbe60a 100644 --- a/tools/c-sdk/README.md +++ b/tools/c-sdk/README.md @@ -54,5 +54,12 @@ RPATH such as `@executable_path/../lib`; the dylib uses `@rpath/libbinding_c.dylib` as its install name. No checkout or Cargo build directory is needed by SDK consumers. -The supported circuit construction and parameter APIs are documented in the -generated header and illustrated in `tests/test_circuit.c`. +Circuit construction, parameters, fermionic algebra, Jordan-Wigner mapping and +checked sparse Pauli algebra are documented in the generated header and +illustrated in `tests/test_circuit.c` and `tests/test_qis_algebra.c`. +`tests/test_density_matrix_targets.c` checks rejection of duplicate targets and +preservation of the density matrix. All three suites run against static and +shared libraries. New checked algebra APIs return error +codes and deliver owned results through output pointers; failed calls leave +outputs unchanged. Initialize object output slots to NULL and free results with +their corresponding functions. diff --git a/tools/ci.py b/tools/ci.py index 0eb347ce..fc5cafea 100644 --- a/tools/ci.py +++ b/tools/ci.py @@ -50,12 +50,12 @@ def versions(tag=None): binding = read_toml(BINDING / "Cargo.toml") python = str(Version(binding["package"]["version"])) require( - "abi3-py310" in binding["dependencies"]["pyo3"]["features"], - "Require abi3-py310", + "abi3-py311" in binding["dependencies"]["pyo3"]["features"], + "Require abi3-py311", ) require( - read_toml(BINDING / "pyproject.toml")["project"]["requires-python"] == ">=3.10", - "Require Python >=3.10", + read_toml(BINDING / "pyproject.toml")["project"]["requires-python"] == ">=3.11", + "Require Python >=3.11", ) for member in ("binding-python", "binding-c", "cqlib"): manifest = read_toml(ROOT / "crates" / member / "Cargo.toml") @@ -105,7 +105,12 @@ def build_and_test(platform=None): shutil.copy2(ROOT / "LICENSE.txt", sdk) shutil.copy2(ROOT / "tools/c-sdk/README.md", sdk / "README.md") (sdk / "tests").mkdir() - shutil.copy2(ROOT / "crates/binding-c/tests/test_circuit.c", sdk / "tests") + for test in ( + "test_circuit.c", + "test_qis_algebra.c", + "test_density_matrix_targets.c", + ): + shutil.copy2(ROOT / "crates/binding-c/tests" / test, sdk / "tests") shutil.copy2(ROOT / "tools/c-sdk/CMakeLists.txt", sdk / "tests") if sys.platform == "darwin": dylib = sdk / "lib/libbinding_c.dylib" @@ -169,8 +174,8 @@ def verify_wheel(directory=DIST): name == "cqlib" and version == Version(versions()[0]), "Wrong wheel version" ) require( - all(t.interpreter == "cp310" and t.abi == "abi3" for t in tags), - "Wheel must use cp310-abi3", + all(t.interpreter == "cp311" and t.abi == "abi3" for t in tags), + "Wheel must use cp311-abi3", ) with tempfile.TemporaryDirectory(prefix="cqlib-wheel-") as temporary: directory = Path(temporary)