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/tests/test_circuit.c b/crates/binding-c/tests/test_circuit.c index ba48098f..aebce651 100644 --- a/crates/binding-c/tests/test_circuit.c +++ b/crates/binding-c/tests/test_circuit.c @@ -251,7 +251,134 @@ static void test_circuit_gate_operation_matrix(void) { } } +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(); 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/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/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/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/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 4df35a39..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>( @@ -1636,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/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/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/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/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/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/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/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.