From 745fb081987e6f4cd052e9fc60529aadf13060d0 Mon Sep 17 00:00:00 2001 From: Chen Xinmiao Date: Wed, 21 Oct 2026 13:45:39 +0800 Subject: [PATCH 1/4] Add block_zxz used to decompose Multiple-qubit gate --- .../compile/transform/decompose/block_zxz.py | 65 ++ .../compile/transform/decompose/block_zxz.pyi | 178 ++++++ .../compile/transform/decompose/block_zxz.rs | 326 ++++++++++ .../transform/decompose/block_zxz/engine.rs | 588 ++++++++++++++++++ .../transform/decompose/block_zxz/matrix.rs | 245 ++++++++ .../transform/decompose/block_zxz/mod.rs | 53 ++ .../transform/decompose/block_zxz/step1.rs | 151 +++++ .../transform/decompose/block_zxz/step2.rs | 179 ++++++ .../transform/decompose/block_zxz/ucrz.rs | 296 +++++++++ .../transform/decompose/block_zxz/vw.rs | 222 +++++++ 10 files changed, 2303 insertions(+) create mode 100644 crates/binding-python/cqlib/compile/transform/decompose/block_zxz.py create mode 100644 crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi create mode 100644 crates/binding-python/src/compile/transform/decompose/block_zxz.rs create mode 100644 crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs create mode 100644 crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs create mode 100644 crates/cqlib-core/src/compile/transform/decompose/block_zxz/mod.rs create mode 100644 crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs create mode 100644 crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs create mode 100644 crates/cqlib-core/src/compile/transform/decompose/block_zxz/ucrz.rs create mode 100644 crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs 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..4acc2b16 --- /dev/null +++ b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.py @@ -0,0 +1,65 @@ +# This code is part of Cqlib. +# +# (C) Copyright China Telecom Quantum Group 2026 +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Block-ZXZ decomposition of general n-qubit unitary matrices. + +Implements the recursive Block-ZXZ decomposition of Krol & Al-Ars, +"Beyond Quantum Shannon: Circuit Construction for General n-Qubit Gates +Based on Block ZXZ-Decomposition" (arXiv:2403.13692), including the +paper's Section 5 CNOT-count optimizations: + +- A.1 (``opt_a1``): each recursion level's two UCRz side CNOTs are folded + into the middle multiplexer via the ``H @ CX = CZ @ H`` identities, + saving 2 CNOTs per level. +- A.2 (``opt_a2``): every two-qubit leaf but the temporally last one is + synthesized with 2 CNOTs plus a rolling diagonal remainder + (Shende-Markov-Bullock "up to diagonal"), saving ``4^(n-2) - 1`` CNOTs. + +With both optimizations enabled (the default) the CNOT count meets the +paper bound ``22/48 * 4^n - 3/2 * 2^n + 5/3`` (n=3 -> 19, n=4 -> 95). + +Example:: + + import numpy as np + from cqlib.compile.transform.decompose.block_zxz import ( + decompose_block_zxz, + block_zxz_cx_count, + ) + + unitary = np.eye(8, dtype=complex) + circuit = decompose_block_zxz(unitary) + assert block_zxz_cx_count(circuit) <= 19 +""" + +from ...._native import compile as _compile_module + +_block_zxz_module = _compile_module.transform.decompose.block_zxz + +BlockZxzDecomposeOptions = _block_zxz_module.BlockZxzDecomposeOptions +decompose_block_zxz = _block_zxz_module.decompose_block_zxz +decompose_block_zxz_with_options = _block_zxz_module.decompose_block_zxz_with_options +block_zxz_step1 = _block_zxz_module.block_zxz_step1 +block_zxz_demux_pair = _block_zxz_module.block_zxz_demux_pair +block_zxz_step3_ucrz_to_circuit = _block_zxz_module.block_zxz_step3_ucrz_to_circuit +block_zxz_is_block_diagonal = _block_zxz_module.block_zxz_is_block_diagonal +block_zxz_cx_count = _block_zxz_module.block_zxz_cx_count + +__all__ = [ + "BlockZxzDecomposeOptions", + "decompose_block_zxz", + "decompose_block_zxz_with_options", + "block_zxz_step1", + "block_zxz_demux_pair", + "block_zxz_step3_ucrz_to_circuit", + "block_zxz_is_block_diagonal", + "block_zxz_cx_count", +] 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..ef09baaa --- /dev/null +++ b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi @@ -0,0 +1,178 @@ +# 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. + +"""Block-ZXZ decomposition of general n-qubit unitary matrices.""" + +from __future__ import annotations + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from cqlib.circuit import Circuit + + +class BlockZxzDecomposeOptions: + """Optimization switches of the paper's Section 5 reductions. + + Args: + opt_a1: Fold each recursion level's two UCRz side CNOTs into the + middle multiplexer (paper 5.2 / Eq. 11; saves 2 CNOTs per + level). + opt_a2: Two-qubit leaf 2-CNOT synthesis plus rolling diagonal + remainders (paper 5.1; saves ``4^(n-2) - 1`` CNOTs). + opt_a2_force: Re-enable A.2 on block-diagonal (controlled) inputs, + where the paper disables it by default. + """ + + 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: + """Options with every optimization disabled (unoptimized pipeline).""" + ... + + def __copy__(self) -> BlockZxzDecomposeOptions: ... + def __deepcopy__(self, memo: dict[int, object]) -> BlockZxzDecomposeOptions: ... + def __eq__(self, other: object) -> bool: ... + + +def decompose_block_zxz(matrix: ArrayLike, atol: float = 1e-10) -> Circuit: + """Decompose a general n-qubit unitary into single-qubit rotations and + CX gates via the recursive Block-ZXZ method. + + Both paper Section 5 optimizations (A.1 + A.2) are enabled by default; + the CNOT count meets the paper bound + ``22/48 * 4^n - 3/2 * 2^n + 5/3`` (n=3 -> 19, n=4 -> 95). + + Args: + matrix: Square power-of-two unitary matrix. + atol: Absolute tolerance of the unitarity and invariant checks. + + Returns: + The assembled :class:`~cqlib.circuit.Circuit`. + + Raises: + ValueError: If ``matrix`` is not a square power-of-two unitary or a + decomposition invariant fails. + """ + ... + + +def decompose_block_zxz_with_options( + matrix: ArrayLike, + atol: float = 1e-10, + *, + options: BlockZxzDecomposeOptions | None = None, +) -> Circuit: + """Decompose a general n-qubit unitary with explicit optimization + switches. + + A.2 is auto-disabled on block-diagonal (controlled-gate) inputs unless + ``options.opt_a2_force`` is set (paper Sec. 6.2 constraint). + + Args: + matrix: Square power-of-two unitary matrix. + atol: Absolute tolerance of the unitarity and invariant checks. + options: Optimization switches; ``None`` selects the fully + optimized default. + + Returns: + The assembled :class:`~cqlib.circuit.Circuit`. + + Raises: + ValueError: If ``matrix`` is invalid or a decomposition invariant + fails. + """ + ... + + +def block_zxz_step1( + matrix: ArrayLike, atol: float = 1e-10 +) -> tuple[ + NDArray[np.complex128], + NDArray[np.complex128], + NDArray[np.complex128], + NDArray[np.complex128], +]: + """Run Block-ZXZ step 1 and return the factors ``(A1, A2, B, C)``. + + Raises: + ValueError: If ``matrix`` is not a valid unitary of at least two + qubits. + """ + ... + + +def block_zxz_demux_pair( + u0: ArrayLike, u1: ArrayLike, atol: float = 1e-10 +) -> tuple[ + NDArray[np.complex128], + NDArray[np.complex128], + NDArray[np.complex128], +]: + """Demultiplex a block pair ``(U0, U1)`` into ``(V, D, W)``. + + The factors satisfy ``U0 = V @ D @ W`` and + ``U1 = V @ D.conj().T @ W``. + + Raises: + ValueError: If the inputs are invalid or the reconstruction check + fails. + """ + ... + + +def block_zxz_step3_ucrz_to_circuit( + d_matrix: ArrayLike, atol: float = 1e-10 +) -> Circuit: + """Expand a diagonal unitary ``D`` into its uniformly controlled Rz + circuit, enacting ``diag(D, D†)``. + + Raises: + ValueError: If ``d_matrix`` is not a diagonal unitary. + """ + ... + + +def block_zxz_is_block_diagonal(matrix: ArrayLike, atol: float = 1e-10) -> bool: + """Return whether ``matrix`` is block-diagonal (controlled-gate shape).""" + ... + + +def block_zxz_cx_count(circuit: Circuit) -> int: + """Count the CX gates of ``circuit`` (nested composite blocks included).""" + ... + + +__all__ = [ + "BlockZxzDecomposeOptions", + "decompose_block_zxz", + "decompose_block_zxz_with_options", + "block_zxz_step1", + "block_zxz_demux_pair", + "block_zxz_step3_ucrz_to_circuit", + "block_zxz_is_block_diagonal", + "block_zxz_cx_count", +] 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..9987463a --- /dev/null +++ b/crates/binding-python/src/compile/transform/decompose/block_zxz.rs @@ -0,0 +1,326 @@ +// This code is part of Cqlib. +// +// (C) Copyright China Telecom Quantum Group 2026 +// +// This code is licensed under the Apache License, Version 2.0. You may +// obtain a copy of this license in the LICENSE.txt file in the root directory +// of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +// +// Any modifications or derivative works of this code must retain this +// copyright notice, and modified files need to carry a notice indicating +// that they have been altered from the originals. + +//! Python bindings for the Block-ZXZ decomposition of general n-qubit +//! unitaries (Krol & Al-Ars, arXiv:2403.13692), including the paper's +//! Section 5 A.1/A.2 CNOT-count optimizations. + +use crate::circuit::PyCircuit; +use cqlib_core::circuit::Circuit; +use cqlib_core::compile::transform::decompose::block_zxz::{ + DecomposeOptions as CoreDecomposeOptions, decompose_block_zxz as core_decompose_block_zxz, + decompose_block_zxz_with_options as core_decompose_block_zxz_with_options, +}; +use num_complex::Complex64; +use numpy::ndarray::Array2; +use numpy::{PyArray2, PyArrayMethods}; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; + +/// Optimization switches of the paper's Section 5 reductions. +/// +/// ``opt_a1`` (paper 5.2 / Eq. 11) folds each recursion level's two UCRz +/// side CNOTs into the middle multiplexer (saves 2 CNOTs per level). +/// ``opt_a2`` (paper 5.1, Shende-Markov-Bullock) decomposes every two-qubit +/// leaf but the temporally last one into a 2-CNOT circuit plus a rolling +/// diagonal remainder (saves ``4^(n-2) - 1`` CNOTs). ``opt_a2_force`` +/// re-enables A.2 on block-diagonal (controlled) inputs, where the paper +/// disables it by default. +#[pyclass( + name = "BlockZxzDecomposeOptions", + module = "cqlib.compile.transform.decompose.block_zxz", + from_py_object +)] +#[derive(Clone, Copy, Debug)] +pub struct PyBlockZxzDecomposeOptions { + pub(crate) inner: CoreDecomposeOptions, +} + +#[pymethods] +impl PyBlockZxzDecomposeOptions { + #[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 { + inner: CoreDecomposeOptions { + opt_a1, + opt_a2, + opt_a2_force, + }, + } + } + + /// A.1: fold each recursion level's two UCRz side CNOTs into the + /// middle multiplexer. + #[getter] + fn opt_a1(&self) -> bool { + self.inner.opt_a1 + } + + /// A.2: two-qubit leaf 2-CNOT synthesis + rolling diagonal remainders. + #[getter] + fn opt_a2(&self) -> bool { + self.inner.opt_a2 + } + + /// Force A.2 on block-diagonal (controlled) inputs. + #[getter] + fn opt_a2_force(&self) -> bool { + self.inner.opt_a2_force + } + + /// Returns options with every optimization disabled (the paper's + /// unoptimized pipeline). + #[staticmethod] + fn none() -> Self { + Self { + inner: CoreDecomposeOptions::none(), + } + } + + fn __repr__(&self) -> String { + let opt = |value: bool| if value { "True" } else { "False" }; + format!( + "BlockZxzDecomposeOptions(opt_a1={}, opt_a2={}, opt_a2_force={})", + opt(self.inner.opt_a1), + opt(self.inner.opt_a2), + opt(self.inner.opt_a2_force) + ) + } + + fn __eq__(&self, other: &Self) -> bool { + self.inner.opt_a1 == other.inner.opt_a1 + && self.inner.opt_a2 == other.inner.opt_a2 + && self.inner.opt_a2_force == other.inner.opt_a2_force + } + + fn __copy__(&self) -> Self { + *self + } + + fn __deepcopy__(&self, _memo: &Bound<'_, PyAny>) -> Self { + *self + } +} + +/// Converts the engine's `String` error into a Python `ValueError` (the +/// original Python project raises `ValueError` on invalid inputs). +fn string_error_to_py_err(message: String) -> pyo3::PyErr { + PyValueError::new_err(message) +} + +/// Converts a Python matrix argument into a complex128 ndarray. +fn extract_complex_matrix( + py: Python<'_>, + matrix: Bound<'_, PyAny>, +) -> pyo3::PyResult> { + let numpy = py.import("numpy")?; + let array = numpy.call_method1("array", (matrix, "complex128"))?; + let array = array.cast_into::>().map_err(|_| { + PyValueError::new_err("matrix must be convertible to a two-dimensional complex128 array") + })?; + Ok(array.to_owned_array()) +} + +/// Wraps an owned core circuit into the public `Circuit` wrapper. +fn circuit_into_py(circuit: Circuit) -> PyCircuit { + PyCircuit::from(circuit) +} + +/// Decomposes a general n-qubit unitary into a `Circuit` of single-qubit +/// rotations and CX gates via the recursive Block-ZXZ method. +/// +/// Both paper Section 5 optimizations (A.1 + A.2) are enabled by default; +/// the resulting CNOT count meets the paper bound +/// ``22/48 * 4^n - 3/2 * 2^n + 5/3`` (n=3 -> 19, n=4 -> 95). +/// +/// Raises: +/// ValueError: If ``matrix`` is not a square power-of-two unitary or a +/// decomposition invariant fails. +#[pyfunction(name = "decompose_block_zxz")] +#[pyo3(signature = (matrix, atol=1e-10))] +pub fn py_decompose_block_zxz( + py: Python<'_>, + matrix: Bound<'_, PyAny>, + atol: f64, +) -> PyResult { + let matrix = extract_complex_matrix(py, matrix)?; + py.detach(move || core_decompose_block_zxz(&matrix, atol)) + .map(|result| circuit_into_py(result.circuit)) + .map_err(string_error_to_py_err) +} + +/// Decomposes a general n-qubit unitary with explicit optimization +/// switches (see `BlockZxzDecomposeOptions`). +/// +/// A.2 is auto-disabled on block-diagonal (controlled-gate) inputs unless +/// ``options.opt_a2_force`` is set (paper Sec. 6.2 constraint). +/// +/// Raises: +/// ValueError: If ``matrix`` is invalid or a decomposition invariant +/// fails. +#[pyfunction(name = "decompose_block_zxz_with_options")] +#[pyo3(signature = (matrix, atol=1e-10, *, options=None))] +pub fn py_decompose_block_zxz_with_options( + py: Python<'_>, + matrix: Bound<'_, PyAny>, + atol: f64, + options: Option, +) -> PyResult { + let matrix = extract_complex_matrix(py, matrix)?; + let options = options.map_or_else(CoreDecomposeOptions::default, |value| value.inner); + py.detach(move || core_decompose_block_zxz_with_options(&matrix, atol, &options)) + .map(|result| circuit_into_py(result.circuit)) + .map_err(string_error_to_py_err) +} + +/// Runs Block-ZXZ step 1 and returns the four sub-block factors +/// ``(A1, A2, B, C)`` as complex128 arrays. +/// +/// Raises: +/// ValueError: If ``matrix`` is not a valid unitary of at least two +/// qubits. +#[pyfunction(name = "block_zxz_step1")] +#[pyo3(signature = (matrix, atol=1e-10))] +pub fn py_block_zxz_step1<'py>( + py: Python<'py>, + matrix: Bound<'_, PyAny>, + atol: f64, +) -> PyResult<( + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, +)> { + let matrix = extract_complex_matrix(py, matrix)?; + let (a1, a2, b, c) = py + .detach(move || { + cqlib_core::compile::transform::decompose::block_zxz::block_zxz_step1(&matrix, atol) + }) + .map_err(string_error_to_py_err)?; + Ok(( + PyArray2::from_owned_array(py, a1), + PyArray2::from_owned_array(py, a2), + PyArray2::from_owned_array(py, b), + PyArray2::from_owned_array(py, c), + )) +} + +/// Demultiplexes a block pair ``(U0, U1)`` into the factors +/// ``(V, D, W)`` with ``U0 = V @ D @ W`` and ``U1 = V @ D.conj().T @ W``. +/// +/// Raises: +/// ValueError: If the inputs are invalid or the reconstruction check +/// fails. +#[pyfunction(name = "block_zxz_demux_pair")] +#[pyo3(signature = (u0, u1, atol=1e-10))] +pub fn py_block_zxz_demux_pair<'py>( + py: Python<'py>, + u0: Bound<'_, PyAny>, + u1: Bound<'_, PyAny>, + atol: f64, +) -> PyResult<( + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, +)> { + let u0 = extract_complex_matrix(py, u0)?; + let u1 = extract_complex_matrix(py, u1)?; + let (v, d, w) = py + .detach(move || { + cqlib_core::compile::transform::decompose::block_zxz::step2::demux_pair(&u0, &u1, atol) + }) + .map_err(string_error_to_py_err)?; + Ok(( + PyArray2::from_owned_array(py, v), + PyArray2::from_owned_array(py, d), + PyArray2::from_owned_array(py, w), + )) +} + +/// Expands a diagonal unitary ``D`` into its uniformly controlled Rz +/// circuit, enacting ``diag(D, D†)``. +/// +/// Raises: +/// ValueError: If ``d_matrix`` is not a diagonal unitary. +#[pyfunction(name = "block_zxz_step3_ucrz_to_circuit")] +#[pyo3(signature = (d_matrix, atol=1e-10))] +pub fn py_block_zxz_step3_ucrz_to_circuit( + py: Python<'_>, + d_matrix: Bound<'_, PyAny>, + atol: f64, +) -> PyResult { + let d_matrix = extract_complex_matrix(py, d_matrix)?; + let circuit = py + .detach(move || { + cqlib_core::compile::transform::decompose::block_zxz::ucrz::step3_ucrz_to_circuit( + &d_matrix, atol, + ) + }) + .map_err(string_error_to_py_err)? + .circuit; + Ok(circuit_into_py(circuit)) +} + +/// Returns whether ``matrix`` is block-diagonal (a controlled-gate shape) +/// within ``atol``. +#[pyfunction(name = "block_zxz_is_block_diagonal")] +#[pyo3(signature = (matrix, atol=1e-10))] +pub fn py_block_zxz_is_block_diagonal( + py: Python<'_>, + matrix: Bound<'_, PyAny>, + atol: f64, +) -> PyResult { + let matrix = extract_complex_matrix(py, matrix)?; + Ok( + cqlib_core::compile::transform::decompose::block_zxz::engine::is_block_diagonal( + &matrix, atol, + ), + ) +} + +/// Counts the CX gates of ``circuit`` (including nested composite-gate +/// blocks). +#[pyfunction(name = "block_zxz_cx_count")] +pub fn py_block_zxz_cx_count(circuit: &PyCircuit) -> usize { + cqlib_core::compile::transform::decompose::block_zxz::vw::count_cx(&circuit.inner) +} + +/// Registers Block-ZXZ bindings as +/// `_native.compile.transform.decompose.block_zxz`. +pub(crate) fn register_block_zxz_module(parent: &Bound<'_, PyModule>) -> PyResult<()> { + let m = PyModule::new(parent.py(), "block_zxz")?; + + m.add_class::()?; + m.add_function(pyo3::wrap_pyfunction!(py_decompose_block_zxz, &m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + py_decompose_block_zxz_with_options, + &m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(py_block_zxz_step1, &m)?)?; + m.add_function(pyo3::wrap_pyfunction!(py_block_zxz_demux_pair, &m)?)?; + m.add_function(pyo3::wrap_pyfunction!( + py_block_zxz_step3_ucrz_to_circuit, + &m + )?)?; + m.add_function(pyo3::wrap_pyfunction!(py_block_zxz_is_block_diagonal, &m)?)?; + m.add_function(pyo3::wrap_pyfunction!(py_block_zxz_cx_count, &m)?)?; + + parent.add_submodule(&m)?; + parent + .py() + .import("sys")? + .getattr("modules")? + .set_item("cqlib._native.compile.transform.decompose.block_zxz", &m)?; + + Ok(()) +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs new file mode 100644 index 00000000..4a2b6936 --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs @@ -0,0 +1,588 @@ +// 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. + +//! Block-ZXZ main flow: recursive tree construction and circuit assembly +//! (step 4) plus the A.1/A.2 optimization passes. +//! +//! Function-by-function mirror of the Python `decompose/block_ZXZ/main.py`, +//! implementing the two optimizations of the paper's Section 5: +//! +//! - **A.1** (`opt_a1`, paper 5.2 / Eq. 11): the middle block pair becomes +//! `B-tilde = diag(W_A V_C, (Z (x) I) W_A B V_C (Z (x) I))`, while the +//! C-side UCRz chain drops its trailing closing CNOT and the A-side chain +//! is time-reversed and drops its leading closing CNOT. By the identities +//! `H CXc = CZ H` and `CXc H = H CZ` the two removed CNOTs are exactly +//! absorbed into the B-tilde demux, saving 2 CNOTs per level. +//! - **A.2** (`opt_a2`, paper 5.1 / Shende-Markov-Bullock "up to diagonal"): +//! every two-qubit leaf but the temporally last one is decomposed into a +//! 2-CNOT circuit plus a pure diagonal remainder (SMB Prop. III.3 +//! construction, see the `vw` module docs); the remainder rolls forward +//! along the circuit's temporal order and merges into the next leaf's +//! synthesis target (the diagonal commutes strictly with every non-leaf +//! gate, so it migrates without any reordering). +//! +//! Leaf (1q/2q) synthesis reuses this crate's `unitary` module, matching the +//! Python project's use of `cqlib`. + +use crate::circuit::{Circuit, Parameter, Qubit}; +use crate::compile::transform::decompose::unitary::synthesize_numeric_1q_unitary; +use ndarray::Array2; +use num_complex::Complex64; + +use super::matrix::Cm; +use super::step1::{assert_square_unitary, block_zxz_step1}; +use super::step2::{ + Step2Result, block_zxz_step2, build_middle_pair, demux_middle_branch_a1, demux_pair, +}; +use super::ucrz::{ + step3_ucrz_from_diagonal, synthesize_ucrz_circuit, synthesize_ucrz_circuit_reduced_tail, + synthesize_ucrz_circuit_reversed_reduced_head, +}; +use super::vw::{synth_leaf_full, synth_two_cnot_with_diagonal}; + +/// Decomposition options (the optimization switches of the paper's +/// Section 5). +#[derive(Debug, Clone, Copy)] +pub struct DecomposeOptions { + /// A.1: fold each recursion level's two UCRz side CNOTs into the middle + /// multiplexer (saves 2 CNOTs per level). + pub opt_a1: bool, + /// A.2: two-qubit leaf 2-CNOT synthesis + diagonal-remainder rolling + /// (saves `4^(n-2) - 1` CNOTs). + pub opt_a2: bool, + /// Re-enables A.2 on block-diagonal (controlled) inputs, where paper + /// Sec. 5.1 disables it by default because the rolling would break the + /// block structure. + pub opt_a2_force: bool, +} + +impl Default for DecomposeOptions { + fn default() -> Self { + DecomposeOptions { + opt_a1: true, + opt_a2: true, + opt_a2_force: false, + } + } +} + +impl DecomposeOptions { + /// All optimizations off (matches the original unoptimized pipeline). + pub fn none() -> Self { + DecomposeOptions { + opt_a1: false, + opt_a2: false, + opt_a2_force: false, + } + } +} + +/// Returns the qubit count `log2(nrows)` of a unitary. +fn num_qubits_of(unitary: &Array2) -> usize { + (unitary.nrows() as f64).log2().round() as usize +} + +/// A node of the recursive decomposition tree. +#[derive(Debug)] +pub enum Node { + /// A 1/2-qubit leaf. + Base(BaseNode), + /// A recursion-layer node. + Recursive(RecursiveNode), +} + +/// A leaf node (the matrix is cached during construction; under A.2 the +/// circuit is filled later by the chain pass). +#[derive(Debug)] +pub struct BaseNode { + pub num_qubits: usize, + /// The leaf's input matrix (used by the A.2 transfer pass). + pub matrix: Cm, + /// The synthesized circuit (1q leaves are synthesized eagerly during + /// the tree build; 2q circuits are filled by `apply_leaf_synthesis`). + pub circuit: Circuit, + /// Synthesis-method marker. + pub method: &'static str, +} + +/// A recursion-layer node. +#[derive(Debug)] +pub struct RecursiveNode { + pub num_qubits: usize, + pub input_unitary: Cm, + pub layer: Layer, + pub children: Vec<(&'static str, Node)>, +} + +/// Result of decomposing a single layer. +#[derive(Debug)] +pub struct Layer { + /// The three UCRz circuits (named `c`/`b`/`a`). + pub step3: LayerStep3, + /// The four sub-unitaries that continue the recursion (named + /// `va`/`vb`/`wb`/`wc`). + pub subunitaries: Vec<(&'static str, Cm)>, + /// The assembly order. + pub assembly: Vec, + /// Whether A.1 was applied in this layer. + pub opt_a1: bool, +} + +/// Container of the three UCRz circuits. +#[derive(Debug)] +pub struct LayerStep3 { + pub c: Circuit, + pub b: Circuit, + pub a: Circuit, +} + +/// One assembly item. +#[derive(Debug, Clone)] +pub enum AssemblyItem { + /// A recursive child circuit (named `wc`/`wb`/`vb`/`va`). + Child(&'static str), + /// A UCRz circuit (named `c`/`b`/`a`). + Ucrz(&'static str), + /// The top-qubit Hadamard. + H, +} + +/// Returns the fixed assembly order of one Block-ZXZ layer (mirrors the +/// Python `get_layer_assembly_plan`). +pub fn get_layer_assembly_plan() -> Vec { + vec![ + AssemblyItem::Child("wc"), + AssemblyItem::Ucrz("c"), + AssemblyItem::H, + AssemblyItem::Child("wb"), + AssemblyItem::Ucrz("b"), + AssemblyItem::Child("vb"), + AssemblyItem::H, + AssemblyItem::Ucrz("a"), + AssemblyItem::Child("va"), + ] +} + +/// Returns whether `unitary` is block-diagonal (a controlled-gate shape, +/// the disable condition for A.2). +pub fn is_block_diagonal(unitary: &Cm, atol: f64) -> bool { + let n = unitary.nrows(); + let half = n / 2; + for i in 0..n { + for j in 0..n { + let in_offdiag = (i < half) != (j < half); + if in_offdiag && unitary[[i, j]].norm() > atol { + return false; + } + } + } + true +} + +/// Collects the four sub-unitaries that continue the recursion from a +/// plain [`block_zxz_step2`](super::step2::block_zxz_step2) result +/// (mirrors the Python `collect_recursive_subunitaries`). +/// +/// Note: this uses the *unoptimized* middle demux of the step-2 result. +/// [`build_block_zxz_layer`] deliberately does not call this helper: when +/// A.1 is enabled the recursion must continue from the B-tilde demux +/// (paper Eq. 11) that also produced the layer's B-side UCRz circuit. +pub fn collect_recursive_subunitaries(step2: &Step2Result) -> Vec<(&'static str, Cm)> { + vec![ + ("va", step2.a_demux.0.clone()), + ("vb", step2.middle_demux.0.clone()), + ("wb", step2.middle_demux.2.clone()), + ("wc", step2.c_demux.2.clone()), + ] +} + +/// Returns whether `unitary` is a 1/2-qubit recursion leaf (mirrors the +/// Python `is_base_case_unitary`). +pub fn is_base_case_unitary(unitary: &Cm, atol: f64) -> Result { + assert_square_unitary(unitary, atol)?; + Ok(unitary.nrows() == 2 || unitary.nrows() == 4) +} + +/// One-qubit leaf synthesis (ZYZ path via the crate's `unitary` module). +fn synth_1q(unitary: &Cm) -> Result<(Circuit, &'static str), String> { + let decomposition = synthesize_numeric_1q_unitary(unitary).map_err(|e| e.to_string())?; + let mut circuit = Circuit::new(1); + circuit + .u( + Qubit::new(0), + Parameter::from(decomposition.theta), + Parameter::from(decomposition.phi), + Parameter::from(decomposition.lambda), + ) + .map_err(|e| e.to_string())?; + circuit.set_global_phase(Parameter::from(decomposition.global_phase)); + Ok((circuit, "1q")) +} + +/// Builds a leaf node (deferred synthesis: the matrix is recorded first and +/// the circuit is filled by `apply_leaf_synthesis` in execution order). +fn build_base_case_node(unitary: &Cm, options: &DecomposeOptions) -> Result { + let num_qubits = num_qubits_of(unitary); + match num_qubits { + 1 => { + let (circuit, method) = synth_1q(unitary)?; + Ok(BaseNode { + num_qubits, + matrix: unitary.clone(), + circuit, + method, + }) + } + 2 => { + // Deferred synthesis: cache the matrix; the circuit is filled + // by the A.2 pass in execution order. With A.2 off, synthesize + // immediately. + if !options.opt_a2 { + let circuit = synth_leaf_full(unitary)?; + Ok(BaseNode { + num_qubits, + matrix: unitary.clone(), + circuit, + method: "2q", + }) + } else { + Ok(BaseNode { + num_qubits, + matrix: unitary.clone(), + circuit: Circuit::new(2), + method: "2q-pending", + }) + } + } + _ => Err("Base case circuit synthesis only supports 1 or 2 qubits.".into()), + } +} + +/// Builds one recursion layer (mirrors the Python `build_block_zxz_layer`, +/// with the A.1 switch). +pub fn build_block_zxz_layer( + unitary: &Cm, + atol: f64, + options: &DecomposeOptions, +) -> Result { + assert_square_unitary(unitary, atol)?; + + let (a1, a2, b, c) = block_zxz_step1(unitary, atol)?; + let step2 = block_zxz_step2(&a1, &a2, &b, &c, atol)?; + let a_demux = &step2.a_demux; + let c_demux = &step2.c_demux; + + let (c_ucrz, a_ucrz, use_a1) = if options.opt_a1 { + // A.1: the C-side chain drops its trailing closing CNOT and the + // A-side chain is time-reversed without its leading closing CNOT; + // each saves one CNOT. + let c_data = step3_ucrz_from_diagonal(&c_demux.1, atol)?; + let a_data = step3_ucrz_from_diagonal(&a_demux.1, atol)?; + let c_circuit = + synthesize_ucrz_circuit_reduced_tail(&c_data.theta, &c_data.controls, c_data.target)?; + let a_circuit = synthesize_ucrz_circuit_reversed_reduced_head( + &a_data.theta, + &a_data.controls, + a_data.target, + )?; + (c_circuit, a_circuit, true) + } else { + let c_data = step3_ucrz_from_diagonal(&c_demux.1, atol)?; + let a_data = step3_ucrz_from_diagonal(&a_demux.1, atol)?; + let c_circuit = synthesize_ucrz_circuit(&c_data.theta, &c_data.controls, c_data.target)?; + let a_circuit = synthesize_ucrz_circuit(&a_data.theta, &a_data.controls, a_data.target)?; + (c_circuit, a_circuit, false) + }; + + // Middle demux: under A.1 use the B-tilde pair (Eq. 11), otherwise the + // regular pair. + let middle_demux = if use_a1 { + demux_middle_branch_a1(&a_demux.2, &b, &c_demux.0, atol)? + } else { + let (u0, u1) = build_middle_pair(&a_demux.2, &b, &c_demux.0); + demux_pair(&u0, &u1, atol)? + }; + let b_ucrz = { + let data = step3_ucrz_from_diagonal(&middle_demux.1, atol)?; + synthesize_ucrz_circuit(&data.theta, &data.controls, data.target)? + }; + + // The recursion sub-unitaries must come from the SAME middle demux that + // produced the layer's B-side UCRz circuit: under A.1 this is the + // B-tilde demux (paper Eq. 11), not the unoptimized demux of + // `block_zxz_step2`. + let subunitaries = vec![ + ("va", a_demux.0.clone()), + ("vb", middle_demux.0.clone()), + ("wb", middle_demux.2.clone()), + ("wc", c_demux.2.clone()), + ]; + + Ok(Layer { + step3: LayerStep3 { + c: c_ucrz, + b: b_ucrz, + a: a_ucrz, + }, + subunitaries, + assembly: get_layer_assembly_plan(), + opt_a1: use_a1, + }) +} + +/// Builds the full recursion tree (mirrors the Python `build_block_zxz_tree`). +pub fn build_block_zxz_tree( + unitary: &Cm, + atol: f64, + options: &DecomposeOptions, +) -> Result { + assert_square_unitary(unitary, atol)?; + + if is_base_case_unitary(unitary, atol)? { + return Ok(Node::Base(build_base_case_node(unitary, options)?)); + } + + let layer = build_block_zxz_layer(unitary, atol, options)?; + let mut children = Vec::new(); + for (name, sub) in &layer.subunitaries { + children.push((*name, build_block_zxz_tree(sub, atol, options)?)); + } + Ok(Node::Recursive(RecursiveNode { + num_qubits: num_qubits_of(unitary), + input_unitary: unitary.clone(), + layer, + children, + })) +} + +/// Snapshots all two-qubit leaf matrices in circuit execution order +/// (depth-first, `wc -> wb -> vb -> va` at each level). +fn collect_2q_leaf_matrices(node: &Node, out: &mut Vec) { + match node { + Node::Base(b) => { + if b.num_qubits == 2 { + out.push(b.matrix.clone()); + } + } + Node::Recursive(r) => { + for name in ["wc", "wb", "vb", "va"] { + if let Some((_, child)) = r.children.iter().find(|(n, _)| *n == name) { + collect_2q_leaf_matrices(child, out); + } + } + } + } +} + +/// Pure-function stage: chain-synthesizes the leaf matrices in execution +/// order with the A.2 diagonal-remainder transfer. +/// +/// The `i`-th leaf's synthesis target is `U_i @ D_in` (`D_in` is the +/// upstream remainder, initially the identity); the synthesis obeys +/// `D_out @ circuit == U_i @ D_in` up to global phase. The remainder +/// `D_out` is a pure diagonal matrix (the inverse phase of the SMB +/// `two_cnot_phase_diagonal` construction plus a global phase) and commutes +/// with every non-leaf gate (Rz/CX/H on higher qubits), so it transfers to +/// the next leaf's input unchanged. The temporally last leaf uses the full +/// 0-3 CX adaptive synthesis to absorb the whole accumulated remainder +/// chain. +fn run_a2_chain(matrices: &[Cm]) -> Result, String> { + use super::matrix::mat_mul; + + let mut circuits = Vec::with_capacity(matrices.len()); + // Upstream diagonal remainder (initially the identity). While + // synthesizing the i-th leaf it is fully absorbed into the target + // `U_i @ D_pending` and replaced by the new synthesis remainder + // `D_out`. + let mut pending = identity_diagonal(); + + for (index, unitary) in matrices.iter().enumerate() { + let is_last = index + 1 == matrices.len(); + let target = if is_identity_diagonal(&pending) { + unitary.clone() + } else { + mat_mul(unitary, &pending) + }; + + if is_last { + circuits.push(synth_leaf_full(&target)?); + } else { + let synthesis = synth_two_cnot_with_diagonal(&target)?; + circuits.push(synthesis.circuit); + pending = synthesis.diagonal_out; + } + } + Ok(circuits) +} + +/// The 4x4 identity diagonal. +fn identity_diagonal() -> Cm { + Array2::eye(4) +} + +/// Returns whether the diagonal gate `d` is numerically the identity. +fn is_identity_diagonal(d: &Cm) -> bool { + for i in 0..4 { + let delta = d[[i, i]] - Complex64::new(1.0, 0.0); + if delta.norm() > 1e-12 { + return false; + } + } + true +} + +/// Write-back stage: writes the synthesized circuits into the two-qubit +/// leaves' `circuit` fields in execution order. +fn write_back_leaf_circuits( + node: &mut Node, + circuits: &mut std::vec::IntoIter, +) -> Result<(), String> { + match node { + Node::Base(b) => { + if b.num_qubits == 2 { + if let Some(circuit) = circuits.next() { + b.circuit = circuit; + b.method = "2q"; + } + } + Ok(()) + } + Node::Recursive(r) => { + for name in ["wc", "wb", "vb", "va"] { + if let Some((_, child)) = r.children.iter_mut().find(|(n, _)| *n == name) { + write_back_leaf_circuits(child, circuits)?; + } + } + Ok(()) + } + } +} + +/// A.2 transfer pass: chain-synthesizes the leaves with 2-CNOT + +/// diagonal-remainder and writes the circuits back in execution order. +fn apply_leaf_synthesis(tree: &mut Node, options: &DecomposeOptions) -> Result<(), String> { + if !options.opt_a2 { + return Ok(()); // Leaves were synthesized eagerly during the build. + } + + let mut matrices = Vec::new(); + collect_2q_leaf_matrices(tree, &mut matrices); + if matrices.len() <= 1 { + // Single leaf (e.g. a 2-qubit input): synthesize fully directly. + let circuits: Vec = matrices + .iter() + .map(synth_leaf_full) + .collect::>()?; + let mut iter = circuits.into_iter(); + write_back_leaf_circuits(tree, &mut iter)?; + return Ok(()); + } + + let circuits = run_a2_chain(&matrices)?; + let mut iter = circuits.into_iter(); + write_back_leaf_circuits(tree, &mut iter)?; + Ok(()) +} + +fn find_child<'a>(node: &'a RecursiveNode, name: &str) -> Option<&'a Node> { + node.children + .iter() + .find(|(n, _)| *n == name) + .map(|(_, c)| c) +} + +fn step3_circuit<'a>(layer: &'a Layer, name: &str) -> Option<&'a Circuit> { + match name { + "c" => Some(&layer.step3.c), + "b" => Some(&layer.step3.b), + "a" => Some(&layer.step3.a), + _ => None, + } +} + +/// Assembles the Block-ZXZ circuit (mirrors the Python +/// `assemble_block_zxz_circuit`). +pub fn assemble_block_zxz_circuit(node: &Node) -> Result { + match node { + Node::Base(b) => Ok(b.circuit.clone()), + Node::Recursive(r) => { + let num_qubits = r.num_qubits; + let mut circuit = Circuit::new(num_qubits); + let child_qubits: Vec = + (0..num_qubits - 1).map(|q| Qubit::new(q as u32)).collect(); + let top = Qubit::new((num_qubits - 1) as u32); + + for item in &r.layer.assembly { + match item { + AssemblyItem::Child(name) => { + let child = + find_child(r, name).ok_or_else(|| format!("missing child {name}"))?; + let child_circuit = assemble_block_zxz_circuit(child)?; + circuit + .compose(&child_circuit, Some(&child_qubits)) + .map_err(|e| e.to_string())?; + } + AssemblyItem::Ucrz(name) => { + let c = step3_circuit(&r.layer, name) + .ok_or_else(|| format!("missing ucrz {name}"))?; + circuit.compose(c, None).map_err(|e| e.to_string())?; + } + AssemblyItem::H => { + circuit.h(top).map_err(|e| e.to_string())?; + } + } + } + Ok(circuit) + } + } +} + +/// Result of a Block-ZXZ decomposition. +#[derive(Debug)] +pub struct DecomposeResult { + pub tree: Node, + pub circuit: Circuit, +} + +/// Returns the recursion tree and assembled circuit (mirrors the Python +/// `decompose_block_zxz`); both paper Section 5 optimizations are enabled +/// by default. +pub fn decompose_block_zxz(unitary: &Cm, atol: f64) -> Result { + decompose_block_zxz_with_options(unitary, atol, &DecomposeOptions::default()) +} + +/// Decomposition entry point with explicit optimization switches. +/// +/// A.2 is auto-disabled on block-diagonal (controlled-gate) inputs unless +/// `options.opt_a2_force` is set (paper Sec. 5.1 constraint). +pub fn decompose_block_zxz_with_options( + unitary: &Cm, + atol: f64, + options: &DecomposeOptions, +) -> Result { + assert_square_unitary(unitary, atol)?; + + // A.2 disable condition: block-diagonal (controlled-gate) input + // (paper 5.1 constraint). + let effective = if options.opt_a2 && !options.opt_a2_force && is_block_diagonal(unitary, atol) { + let mut o = *options; + o.opt_a2 = false; + o + } else { + *options + }; + + let mut tree = build_block_zxz_tree(unitary, atol, &effective)?; + apply_leaf_synthesis(&mut tree, &effective)?; + let circuit = assemble_block_zxz_circuit(&tree)?; + Ok(DecomposeResult { tree, circuit }) +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs new file mode 100644 index 00000000..15b0087a --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs @@ -0,0 +1,245 @@ +// 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. + +//! Complex-matrix utilities for the Block-ZXZ decomposition. +//! +//! Mirrors the `numpy`/`scipy` matrix operations of the Python project. +//! `ndarray::Array2` is the primary matrix type (consistent with +//! the rest of the crate); `faer` is only borrowed for diagonalization and +//! singular-value decomposition. + +use ndarray::{Array2, s}; +use num_complex::Complex64; + +/// Complex matrix alias. +pub type Cm = Array2; + +/// Builds the `n x n` identity matrix. +pub fn eye(n: usize) -> Cm { + Array2::eye(n) +} + +/// Matrix product `A @ B`. +#[inline] +pub fn mat_mul(a: &Cm, b: &Cm) -> Cm { + a.dot(b) +} + +/// Conjugate transpose `A^H`. +#[inline] +pub fn adjoint(a: &Cm) -> Cm { + a.t().mapv(|z| z.conj()) +} + +/// Builds a diagonal matrix from a list of diagonal values. +pub fn diagonal_from_values(values: &[Complex64]) -> Cm { + let n = values.len(); + let mut out = Array2::::zeros((n, n)); + for (i, &v) in values.iter().enumerate() { + out[[i, i]] = v; + } + out +} + +/// Builds the block-diagonal matrix `diag(top_left, bottom_right)`. +pub fn block_diag(top_left: &Cm, bottom_right: &Cm) -> Cm { + let td = top_left.dim().0; + let bd = bottom_right.dim().0; + let n = td + bd; + let mut out = Array2::::zeros((n, n)); + out.slice_mut(s![..td, ..td]).assign(top_left); + out.slice_mut(s![td.., td..]).assign(bottom_right); + out +} + +/// Maximum elementwise absolute difference (used for allclose checks). +pub fn max_abs_diff(a: &Cm, b: &Cm) -> f64 { + let mut m = 0.0f64; + for ((i, j), &av) in a.indexed_iter() { + let d = (av - b[[i, j]]).norm(); + if d > m { + m = d; + } + } + m +} + +/// Returns whether `A` is unitary within the `atol` tolerance. +pub fn is_unitary(a: &Cm, atol: f64) -> bool { + if a.nrows() != a.ncols() { + return false; + } + let n = a.nrows(); + max_abs_diff(&mat_mul(&adjoint(a), a), &eye(n)) <= atol +} + +/// Returns whether `A` is diagonal within the `atol` tolerance. +pub fn is_diagonal(a: &Cm, atol: f64) -> bool { + let (r, c) = a.dim(); + for i in 0..r { + for j in 0..c { + if i != j && a[[i, j]].norm() > atol { + return false; + } + } + } + true +} + +// ---- faer conversions ---- + +/// Copies an ndarray matrix into a faer matrix. +pub fn to_faer(a: &Cm) -> faer::Mat { + let (r, c) = a.dim(); + faer::Mat::::from_fn(r, c, |i, j| a[[i, j]]) +} + +/// Copies a faer matrix reference into an ndarray matrix. +pub fn from_faer(m: &faer::MatRef<'_, Complex64>) -> Cm { + Array2::from_shape_fn((m.nrows(), m.ncols()), |(i, j)| m[(i, j)]) +} + +// ---- Numeric decompositions (mirroring numpy.linalg.svd / scipy.linalg.schur) ---- + +/// Polar decomposition through the SVD: returns `(S, U_polar)` with +/// `matrix ~ S @ U_polar`. +/// +/// Mirrors the Python `polar_from_svd`: `X = U Sigma V^H`, +/// `S = U Sigma U^H`, `U_polar = U V^H`. +pub fn polar_from_svd(matrix: &Cm) -> (Cm, Cm) { + let fm = to_faer(matrix); + let svd = fm.svd().expect("SVD failed"); + let u = from_faer(&svd.U()); + let v = from_faer(&svd.V()); + let s_vals: Vec = fm.singular_values().expect("singular values failed"); + let sigma = diagonal_from_real(&s_vals); + let s_factor = mat_mul(&mat_mul(&u, &sigma), &adjoint(&u)); + let u_polar = mat_mul(&u, &adjoint(&v)); + (s_factor, u_polar) +} + +/// Eigen (Schur-style) diagonalization of a complex unitary matrix. +/// +/// Returns `(Q, D)` with `matrix ~ Q D Q^H` and `D` the diagonal matrix of +/// eigenvalues. Mirrors the Python `schur_unitary_diagonalize` +/// (`scipy.linalg.schur` with `output="complex"`). +/// +/// Degenerate-spectrum repair: faer's complex EVD does not guarantee that +/// eigenvectors of a repeated eigenvalue are mutually orthogonal (a normal +/// matrix is theoretically unitarily diagonalizable). Columns are grouped +/// by eigenvalue clusters and re-orthonormalized within each group by a +/// modified Gram-Schmidt pass; an orthonormal basis of a degenerate +/// subspace still spans the same eigenspace, so the diagonalization +/// property is preserved, and subspaces of distinct eigenvalues stay +/// (numerically) orthogonal by normality. +pub fn schur_unitary_diagonalize(matrix: &Cm) -> (Cm, Cm) { + let fm = to_faer(matrix); + let eig = fm.eigen().expect("EVD failed"); + let q_raw = from_faer(&eig.U()); + let evals: Vec = fm.eigenvalues().expect("eigenvalues failed"); + let q = reorthogonalize_degenerate_eigenvectors(&q_raw, &evals); + let d = diagonal_from_values(&evals); + (q, d) +} + +/// Re-orthonormalizes eigenvectors inside degenerate subspaces (see the +/// documentation of [`schur_unitary_diagonalize`]). +/// +/// Eigenvectors of the same eigenvalue cluster are processed by a modified +/// Gram-Schmidt pass over the complex inner product; orthogonality across +/// clusters is naturally preserved by the spectral property of normal +/// matrices. Exact degeneracies on the unit circle jitter at the `~1e-15` +/// level in floating point while distinct eigenvalues are usually separated +/// by `O(0.1)`, so a `1e-7` clustering tolerance is safe. The function does +/// not move any eigenvector out of its eigenspace, so `M = Q D Q^H` still +/// holds. +fn reorthogonalize_degenerate_eigenvectors(q: &Cm, evals: &[Complex64]) -> Cm { + let n = q.ncols(); + debug_assert_eq!(q.nrows(), n); + debug_assert_eq!(evals.len(), n); + + const CLUSTER_TOL: f64 = 1e-7; + + // Clustering: columns of the same eigenvalue (exact degeneracy on the + // unit circle plus floating-point jitter) join the same group. + let mut groups: Vec> = Vec::new(); + for col in 0..n { + let mut placed = false; + for group in groups.iter_mut() { + if (evals[group[0]] - evals[col]).norm() <= CLUSTER_TOL { + group.push(col); + placed = true; + break; + } + } + if !placed { + groups.push(vec![col]); + } + } + + let mut out = q.clone(); + for group in &groups { + if group.len() <= 1 { + continue; + } + // Modified Gram-Schmidt within the group; the subspace is unchanged. + for (pos, &col) in group.iter().enumerate() { + let mut v: Vec = (0..q.nrows()).map(|r| out[[r, col]]).collect(); + for &prev in group.iter().take(pos) { + let mut proj = Complex64::new(0.0, 0.0); + for r in 0..q.nrows() { + proj += out[[r, prev]].conj() * v[r]; + } + for r in 0..q.nrows() { + v[r] -= proj * out[[r, prev]]; + } + } + let norm: f64 = v.iter().map(|z| z.norm_sqr()).sum::().sqrt(); + if norm > 1e-12 { + for r in 0..q.nrows() { + out[[r, col]] = v[r] / norm; + } + } + // A tiny norm keeps the original vector: faer guarantees it is a + // non-zero eigenvector, and near-linear dependence within the + // group cannot be repaired by GS but is no worse than before. + } + } + out +} + +/// Builds a complex diagonal matrix from real values (zero imaginary parts). +fn diagonal_from_real(values: &[f64]) -> Cm { + let v: Vec = values.iter().map(|&x| Complex64::new(x, 0.0)).collect(); + diagonal_from_values(&v) +} + +/// Builds a diagonal unitary square root from unit-modulus eigenvalues. +/// +/// Mirrors the Python `build_unitary_diagonal_sqrt`: +/// `normalized = e / |e|`, `phase = exp(0.5j * arg(normalized))`. +pub fn build_unitary_diagonal_sqrt(eigenvalues: &Cm) -> Cm { + let n = eigenvalues.nrows(); + let mut d = Array2::::zeros((n, n)); + for i in 0..n { + let e = eigenvalues[[i, i]]; + let mag = e.norm(); + let normalized = if mag > 0.0 { + e / mag + } else { + Complex64::new(1.0, 0.0) + }; + // sqrt(e^{i theta}) = e^{i theta / 2} + d[[i, i]] = normalized.sqrt(); + } + d +} 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..a3c952fa --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/mod.rs @@ -0,0 +1,53 @@ +// 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. + +//! # Block-ZXZ decomposition +//! +//! Rust implementation of the Block-ZXZ quantum unitary decomposition +//! (including the paper's A.1/A.2 optimizations). +//! +//! This mirrors the Python project `decompose/block_ZXZ` and the paper +//! *Krol & Al-Ars, "Beyond Quantum Shannon: Circuit Construction for +//! General n-Qubit Gates Based on Block ZXZ-Decomposition" +//! (arXiv:2403.13692)*: +//! +//! - [`step1`]: block splitting + polar decomposition + solving `A1/A2/B/C` +//! - [`step2`]: Schur-style diagonalization + demultiplexing; includes the +//! A.1-optimized `B-tilde` middle pair +//! - [`ucrz`]: Gray-code expansion of uniformly controlled `Rz` gates; +//! includes the A.1 CNOT-reduced chain variants +//! - [`vw`]: A.2 two-qubit 2-CNOT + diagonal-remainder synthesis +//! (Vatan-Williams style construction) +//! - [`engine`]: recursive tree construction, circuit assembly, and the +//! A.1/A.2 optimization passes +//! - [`matrix`]: complex matrix operations and numeric decomposition helpers +//! +//! With both optimizations enabled (the default) the CNOT count satisfies +//! the paper bound `c_n <= 22/48 * 4^n - 3/2 * 2^n + 5/3` +//! (n = 3 -> 19, n = 4 -> 95). +//! +//! Leaf (1q/2q) synthesis reuses the crate's [`super::unitary`] module, the +//! same primitives the Python project reaches through `cqlib`. + +pub mod engine; +pub mod matrix; +pub mod step1; +pub mod step2; +pub mod ucrz; +pub mod vw; + +pub use engine::{ + DecomposeOptions, DecomposeResult, Node, decompose_block_zxz, decompose_block_zxz_with_options, +}; +pub use step1::block_zxz_step1; +pub use step2::block_zxz_step2; +pub use ucrz::step3_ucrz_to_circuit; diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs new file mode 100644 index 00000000..d77292d9 --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs @@ -0,0 +1,151 @@ +// 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. + +//! Block-ZXZ step 1: block splitting + polar decomposition + solving the +//! factors `A1, A2, B, C`. +//! +//! Function-by-function mirror of the Python `decompose/block_ZXZ/step1.py`. + +use super::matrix::{Cm, adjoint, eye, is_unitary, mat_mul}; +use ndarray::s; +use num_complex::Complex64; + +/// Returns whether `value` is a positive power of two. +pub fn is_power_of_two(value: usize) -> bool { + value > 0 && (value & (value - 1)) == 0 +} + +/// Returns whether `matrix` is unitary within `atol`. +pub fn is_matrix_unitary(matrix: &Cm, atol: f64) -> bool { + is_unitary(matrix, atol) +} + +/// Returns whether `matrix` is diagonal within `atol`. +pub fn is_matrix_diagonal(matrix: &Cm, atol: f64) -> bool { + let (r, c) = matrix.dim(); + for i in 0..r { + for j in 0..c { + if i != j && matrix[[i, j]].norm() > atol { + return false; + } + } + } + true +} + +/// Validates that the input is a `2^n x 2^n` unitary matrix. +/// +/// Mirrors the Python `assert_square_unitary`; returns `Err(String)` on +/// failure. +pub fn assert_square_unitary(matrix: &Cm, atol: f64) -> Result<(), String> { + if matrix.ndim() != 2 { + return Err("Input matrix must be two-dimensional.".into()); + } + let (rows, cols) = matrix.dim(); + if rows != cols { + return Err("Input matrix must be square.".into()); + } + if !is_power_of_two(rows) { + return Err("Input matrix dimension must be a power of two.".into()); + } + if !is_unitary(matrix, atol) { + return Err("Input matrix must be unitary.".into()); + } + Ok(()) +} + +/// Splits `unitary` into four equal blocks along the most significant qubit. +/// +/// Mirrors the Python `split_unitary_blocks`; returns `(X, Y, U21, U22)`. +pub fn split_unitary_blocks(unitary: &Cm) -> (Cm, Cm, Cm, Cm) { + assert_square_unitary(unitary, 1e-10).expect("invalid unitary"); + let dim = unitary.nrows(); + let half = dim / 2; + ( + unitary.slice(s![..half, ..half]).to_owned(), + unitary.slice(s![..half, half..]).to_owned(), + unitary.slice(s![half.., ..half]).to_owned(), + unitary.slice(s![half.., half..]).to_owned(), + ) +} + +/// Polar decomposition through the SVD; returns `(S, U_polar)`. +pub fn polar_from_svd(matrix: &Cm) -> (Cm, Cm) { + super::matrix::polar_from_svd(matrix) +} + +/// Computes the Block-ZXZ factor `C`: `C = -i * Ux^H @ Uy`. +pub fn compute_c_from_polar(u_x: &Cm, u_y: &Cm) -> Cm { + let mut c = mat_mul(&adjoint(u_x), u_y); + c *= Complex64::new(0.0, -1.0); + c +} + +/// Computes the Block-ZXZ factor `A1 = (Sx + i Sy) @ Ux`. +pub fn compute_a1(s_x: &Cm, s_y: &Cm, u_x: &Cm) -> Cm { + let mut inner = s_x.clone(); + let iy = s_y.mapv(|z| Complex64::new(0.0, 1.0) * z); + inner = inner + &iy; + mat_mul(&inner, u_x) +} + +/// Computes the Block-ZXZ factor `A2 = U21 + U22 @ (i Uy^H Ux)`. +pub fn compute_a2(u21: &Cm, u22: &Cm, u_y: &Cm, u_x: &Cm) -> Cm { + let t = mat_mul(&adjoint(u_y), u_x).mapv(|z| Complex64::new(0.0, 1.0) * z); + let t = mat_mul(u22, &t); + u21 + &t +} + +/// Computes the Block-ZXZ factor `B = 2 A1^H @ X - I`. +pub fn compute_b(a1: &Cm, x: &Cm) -> Cm { + let identity = eye(x.nrows()); + let t = mat_mul(&adjoint(a1), x).mapv(|z| z * 2.0); + t - &identity +} + +/// Validates that the step-1 outputs `A1/A2/B/C` are all unitary. +pub fn assert_step1_outputs_unitary( + a1: &Cm, + a2: &Cm, + b: &Cm, + c: &Cm, + atol: f64, +) -> Result<(), String> { + for (name, m) in [("A1", a1), ("A2", a2), ("B", b), ("C", c)] { + if !is_unitary(m, atol) { + return Err(format!("{name} is not unitary within tolerance {atol}.")); + } + } + Ok(()) +} + +/// Runs Block-ZXZ step 1 and returns `(A1, A2, B, C)`. +pub fn block_zxz_step1(unitary: &Cm, atol: f64) -> Result<(Cm, Cm, Cm, Cm), String> { + assert_square_unitary(unitary, atol)?; + let n = unitary.nrows(); + let num_qubits = (n as f64).log2().round() as usize; + if num_qubits < 2 { + return Err("Block-ZXZ Step 1 expects at least a 2-qubit unitary.".into()); + } + + let (x, y, u21, u22) = split_unitary_blocks(unitary); + let (s_x, u_x) = polar_from_svd(&x); + let (s_y, u_y) = polar_from_svd(&y); + + let c = compute_c_from_polar(&u_x, &u_y); + let a1 = compute_a1(&s_x, &s_y, &u_x); + let a2 = compute_a2(&u21, &u22, &u_y, &u_x); + let b = compute_b(&a1, &x); + + assert_step1_outputs_unitary(&a1, &a2, &b, &c, atol)?; + Ok((a1, a2, b, c)) +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs new file mode 100644 index 00000000..528bd74c --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs @@ -0,0 +1,179 @@ +// 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. + +//! Block-ZXZ step 2: demultiplexing. +//! +//! Function-by-function mirror of the Python `decompose/block_ZXZ/step2.py`. + +use super::matrix::{Cm, adjoint, eye, mat_mul, max_abs_diff}; +use super::step1::{assert_square_unitary, is_matrix_diagonal, is_matrix_unitary}; + +/// Schur-style diagonalization of a unitary matrix; returns `(Q, D)`. +/// +/// Mirrors the Python `schur_unitary_diagonalize`. +pub fn schur_unitary_diagonalize(matrix: &Cm, atol: f64) -> Result<(Cm, Cm), String> { + assert_square_unitary(matrix, atol)?; + Ok(super::matrix::schur_unitary_diagonalize(matrix)) +} + +/// Builds the diagonal unitary square root `D` from unit-modulus eigenvalues. +/// +/// Mirrors the Python `build_unitary_diagonal_sqrt`. +pub fn build_unitary_diagonal_sqrt(eigenvalues: &Cm) -> Cm { + super::matrix::build_unitary_diagonal_sqrt(eigenvalues) +} + +/// Validates a demultiplexing result against its defining equations. +fn validate_demux_result( + u0: &Cm, + u1: &Cm, + v: &Cm, + d: &Cm, + w: &Cm, + atol: f64, +) -> Result<(), String> { + if !is_matrix_unitary(v, atol) { + return Err("Demux factor V is not unitary.".into()); + } + if !is_matrix_unitary(w, atol) { + return Err("Demux factor W is not unitary.".into()); + } + if !is_matrix_diagonal(d, atol) { + return Err("Demux factor D is not diagonal.".into()); + } + if !is_matrix_unitary(d, atol) { + return Err("Demux factor D is not unitary.".into()); + } + let left = mat_mul(&mat_mul(v, d), w); + let right = mat_mul(&mat_mul(v, &adjoint(d)), w); + if max_abs_diff(&left, u0) > atol { + return Err("Demux reconstruction of U0 failed.".into()); + } + if max_abs_diff(&right, u1) > atol { + return Err("Demux reconstruction of U1 failed.".into()); + } + Ok(()) +} + +/// Demultiplexes `diag(U0, U1) = diag(V, V) @ diag(D, D†) @ diag(W, W)` +/// into the factors `(V, D, W)`. +/// +/// Mirrors the Python `demux_pair`. +pub fn demux_pair(u0: &Cm, u1: &Cm, atol: f64) -> Result<(Cm, Cm, Cm), String> { + assert_square_unitary(u0, atol)?; + assert_square_unitary(u1, atol)?; + if u0.dim() != u1.dim() { + return Err("U0 and U1 must have the same shape.".into()); + } + + let m_matrix = mat_mul(u0, &adjoint(u1)); + let (v_factor, eigenvalues) = schur_unitary_diagonalize(&m_matrix, atol)?; + let d_factor = build_unitary_diagonal_sqrt(&eigenvalues); + let w_factor = mat_mul(&mat_mul(&d_factor, &adjoint(&v_factor)), u1); + + validate_demux_result(u0, u1, &v_factor, &d_factor, &w_factor, atol)?; + Ok((v_factor, d_factor, w_factor)) +} + +/// Demultiplexes the A branch `(A1, A2)`. +pub fn demux_a_branch(a1: &Cm, a2: &Cm, atol: f64) -> Result<(Cm, Cm, Cm), String> { + demux_pair(a1, a2, atol) +} + +/// Demultiplexes the C branch `(I, C)`. +pub fn demux_c_branch(c: &Cm, atol: f64) -> Result<(Cm, Cm, Cm), String> { + assert_square_unitary(c, atol)?; + let identity = eye(c.nrows()); + demux_pair(&identity, c, atol) +} + +/// Builds the middle block pair absorbing `W_A` and `V_C`: +/// `(W_A @ V_C, W_A @ B @ V_C)`. +pub fn build_middle_pair(w_a: &Cm, b: &Cm, v_c: &Cm) -> (Cm, Cm) { + (mat_mul(w_a, v_c), mat_mul(&mat_mul(w_a, b), v_c)) +} + +/// Demultiplexes the middle block pair. +pub fn demux_middle_branch(w_a: &Cm, b: &Cm, v_c: &Cm, atol: f64) -> Result<(Cm, Cm, Cm), String> { + let (u0, u1) = build_middle_pair(w_a, b, v_c); + demux_pair(&u0, &u1, atol) +} + +/// Builds `Z (x) I` acting on the MSB of a `sub_qubits`-qubit block. +/// +/// The matrix is `2^{sub_qubits} x 2^{sub_qubits}` with `+1` on the first +/// half of the diagonal and `-1` on the second half. +fn z_on_subblock_msb(sub_qubits: usize) -> Cm { + let dim = 1usize << sub_qubits; + let half = dim / 2; + let mut z = super::matrix::eye(dim); + for i in half..dim { + z[[i, i]] = num_complex::Complex64::new(-1.0, 0.0); + } + z +} + +/// Builds the A.1-optimized middle block pair (paper Eq. 11). +/// +/// `B-tilde = diag(W_A V_C, (Z (x) I) W_A B V_C (Z (x) I))` where `Z (x) I` +/// acts on the MSB of the `(n-1)`-qubit sub-block. The two closing CNOTs +/// removed from the UCRz chains are absorbed into this pair's multiplexer +/// through the identities `H @ CXc = CZ @ H` and `CXc @ H = H @ CZ`. +pub fn build_middle_pair_a1(w_a: &Cm, b: &Cm, v_c: &Cm) -> (Cm, Cm) { + let sub_qubits = (w_a.nrows() as f64).log2().round() as usize; + let z = z_on_subblock_msb(sub_qubits); + let u0 = mat_mul(w_a, v_c); + let inner = mat_mul(&mat_mul(w_a, b), v_c); + let u1 = mat_mul(&mat_mul(&z, &inner), &z); + (u0, u1) +} + +/// Demultiplexes the A.1-optimized middle block pair. +pub fn demux_middle_branch_a1( + w_a: &Cm, + b: &Cm, + v_c: &Cm, + atol: f64, +) -> Result<(Cm, Cm, Cm), String> { + let (u0, u1) = build_middle_pair_a1(w_a, b, v_c); + demux_pair(&u0, &u1, atol) +} + +/// Result of Block-ZXZ step 2 (mirrors the Python `dict` return value). +#[derive(Debug, Clone)] +pub struct Step2Result { + /// `(V, D, W)` of the A branch. + pub a_demux: (Cm, Cm, Cm), + /// `(V, D, W)` of the C branch. + pub c_demux: (Cm, Cm, Cm), + /// Middle pair `(U0_mid, U1_mid)`. + pub middle_pair: (Cm, Cm), + /// `(V, D, W)` of the middle branch. + pub middle_demux: (Cm, Cm, Cm), +} + +/// Runs Block-ZXZ step 2. +/// +/// Mirrors the Python `block_zxz_step2`. +pub fn block_zxz_step2(a1: &Cm, a2: &Cm, b: &Cm, c: &Cm, atol: f64) -> Result { + let a_demux = demux_a_branch(a1, a2, atol)?; + let c_demux = demux_c_branch(c, atol)?; + let middle_pair = build_middle_pair(&a_demux.2, b, &c_demux.0); + let middle_demux = demux_pair(&middle_pair.0, &middle_pair.1, atol)?; + + Ok(Step2Result { + a_demux, + c_demux, + middle_pair, + middle_demux, + }) +} 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..fb84285f --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/ucrz.rs @@ -0,0 +1,296 @@ +// 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. + +//! Block-ZXZ step 3: Gray-code expansion of uniformly controlled `Rz` +//! (UCRz) gates. +//! +//! Function-by-function mirror of the Python `decompose/block_ZXZ/ucrz.py`. + +use super::matrix::Cm; +use super::step1::{is_matrix_diagonal, is_matrix_unitary}; +use crate::circuit::{Circuit, Qubit}; +use num_complex::Complex64; + +/// Returns the binary reflected Gray code of `index`. +pub fn gray_code(index: usize) -> usize { + index ^ (index >> 1) +} + +/// Returns the Gray-code sequence of length `2^k`. +pub fn gray_code_sequence(num_controls: usize) -> Vec { + (0..(1usize << num_controls)).map(gray_code).collect() +} + +/// Returns the local CNOT control switching order. +/// +/// Uses the local numbering convention `0..num_controls-1` and includes the +/// closing CNOT (the cyclic transition between the last and first codes). +pub fn gray_control_positions(num_controls: usize) -> Vec { + if num_controls == 0 { + return Vec::new(); + } + let sequence = gray_code_sequence(num_controls); + let len = sequence.len(); + let mut controls = Vec::with_capacity(len); + for index in 0..len { + let current = sequence[index]; + let next = sequence[(index + 1) % len]; + let diff = current ^ next; + controls.push(diff.trailing_zeros() as usize); + } + controls +} + +/// Parity of the bitwise inner product (popcount of `left & right` mod 2). +fn binary_dot_parity(left: usize, right: usize) -> usize { + (left & right).count_ones() as usize % 2 +} + +/// Builds the Gray matrix `M^k` (real matrix, +/// `M[i, j] = (-1)^{bit(i) . gray(j)}`). +pub fn gray_matrix(num_controls: usize) -> Cm { + let dim = 1usize << num_controls; + let gray_codes = gray_code_sequence(num_controls); + let mut out = Cm::zeros((dim, dim)); + for row in 0..dim { + for (col, &gray) in gray_codes.iter().enumerate() { + let sign = if binary_dot_parity(row, gray) == 0 { + 1.0 + } else { + -1.0 + }; + out[[row, col]] = Complex64::new(sign, 0.0); + } + } + out +} + +/// Extracts the UCRz target angles `alpha = -2 * arg(D)` from a diagonal +/// unitary `D`. +pub fn extract_ucrz_alpha_from_diagonal(d_matrix: &Cm, atol: f64) -> Result, String> { + let (r, c) = d_matrix.dim(); + if r != c { + return Err("D must be a square matrix.".into()); + } + if !is_matrix_diagonal(d_matrix, atol) { + return Err("D must be diagonal.".into()); + } + if !is_matrix_unitary(d_matrix, atol) { + return Err("D must be unitary.".into()); + } + Ok((0..r).map(|i| -2.0 * d_matrix[[i, i]].arg()).collect()) +} + +/// Solves the Gray-code linear system `M^k theta = alpha`; returns +/// `(theta, M^k)`. +pub fn solve_ucrz_theta_from_alpha(alpha: &[f64]) -> Result<(Vec, Cm), String> { + if !is_power_of_two(alpha.len()) { + return Err("alpha length must be a power of two.".into()); + } + let num_controls = (alpha.len() as f64).log2().round() as usize; + let m = gray_matrix(num_controls); + // theta = (M^T @ alpha) / 2^k + let dim = alpha.len(); + let mut theta = vec![0.0f64; dim]; + for row in 0..dim { + let mut sum = 0.0; + for (col, &a) in alpha.iter().enumerate() { + sum += m[[col, row]].re * a; + } + theta[row] = sum / (dim as f64); + } + Ok((theta, m)) +} + +fn is_power_of_two(value: usize) -> bool { + value > 0 && (value & (value - 1)) == 0 +} + +/// Derives the UCRz numeric description from `D` (mirrors the Python +/// `step3_ucrz_from_diagonal`). +pub fn step3_ucrz_from_diagonal(d_matrix: &Cm, atol: f64) -> Result { + let alpha = extract_ucrz_alpha_from_diagonal(d_matrix, atol)?; + let (theta, gray_matrix) = solve_ucrz_theta_from_alpha(&alpha)?; + let num_controls = (alpha.len() as f64).log2().round() as usize; + Ok(UcrzData { + alpha, + theta, + gray_codes: gray_code_sequence(num_controls), + controls: gray_control_positions(num_controls), + gray_matrix, + num_controls, + target: num_controls, + }) +} + +/// Synthesizes a local UCRz circuit from the Gray-expanded angles. +/// +/// Mirrors the Python `synthesize_ucrz_circuit`. +pub fn synthesize_ucrz_circuit( + theta: &[f64], + controls: &[usize], + target: usize, +) -> Result { + if theta.is_empty() { + return Err("theta must contain at least one rotation angle.".into()); + } + if !is_power_of_two(theta.len()) { + return Err("theta length must be a power of two.".into()); + } + let num_controls = (theta.len() as f64).log2().round() as usize; + + if num_controls == 0 { + if !controls.is_empty() { + return Err("For zero controls, controls must be empty.".into()); + } + if target != 0 { + return Err("For zero controls, the local target must be 0.".into()); + } + let mut circuit = Circuit::new(1); + circuit + .rz(Qubit::new(0), theta[0]) + .map_err(|e| e.to_string())?; + return Ok(circuit); + } + + if controls.len() != theta.len() { + return Err("controls and theta must have the same length.".into()); + } + let expected_controls = gray_control_positions(num_controls); + if controls != &expected_controls[..] { + return Err("controls must follow the local Gray-code convention.".into()); + } + if target != num_controls { + return Err("Under local numbering, target must equal num_controls.".into()); + } + + let mut circuit = Circuit::new(num_controls + 1); + for (&angle, &control) in theta.iter().zip(controls.iter()) { + circuit + .rz(Qubit::new(target as u32), angle) + .map_err(|e| e.to_string())?; + circuit + .cx(Qubit::new(control as u32), Qubit::new(target as u32)) + .map_err(|e| e.to_string())?; + } + Ok(circuit) +} + +/// A.1 optimization: the UCRz chain with the trailing closing CNOT removed +/// (used for the C-side chain). +/// +/// The standard chain enacts, in time order, +/// `[Rz(t0), C0, Rz(t1), C1, ..., Rz(tm), CXc]` whose matrix is +/// `M = CXc @ Rest`; this function returns the circuit for `Rest` (one CNOT +/// fewer). During layer assembly the missing CNOT is absorbed into the +/// B-tilde demultiplexer via the identity `H @ CXc = CZ @ H`. +pub fn synthesize_ucrz_circuit_reduced_tail( + theta: &[f64], + controls: &[usize], + target: usize, +) -> Result { + let mut circuit = synthesize_ucrz_circuit(theta, controls, target)?; + // Drop the temporally last gate (the closing CX). + let n = circuit.operations().len(); + circuit.remove_operation(n - 1).map_err(|e| e.to_string())?; + Ok(circuit) +} + +/// A.1 optimization: the time-reversed UCRz chain without the leading +/// closing CNOT (used for the A-side chain). +/// +/// Because every `Rz` and `CX` matrix is symmetric, the fully reversed chain +/// `[CXc, Rz(tm), C(m-1), Rz(t(m-1)), ..., C0, Rz(t0)]` implements the very +/// same diagonal unitary as the forward chain. This function drops the +/// leading `CXc` (absorbed next to the Hadamard on its earlier side through +/// `CXc @ H = H @ CZ` into the B-tilde demultiplexer) and returns the rest. +pub fn synthesize_ucrz_circuit_reversed_reduced_head( + theta: &[f64], + controls: &[usize], + target: usize, +) -> Result { + if theta.is_empty() || !is_power_of_two(theta.len()) { + return Err("theta length must be a positive power of two.".into()); + } + let num_controls = (theta.len() as f64).log2().round() as usize; + + if num_controls == 0 { + // A single Rz has no CNOT to remove. + let mut circuit = Circuit::new(1); + circuit + .rz(Qubit::new(0), theta[0]) + .map_err(|e| e.to_string())?; + return Ok(circuit); + } + + if controls.len() != theta.len() { + return Err("controls and theta must have the same length.".into()); + } + if controls != &gray_control_positions(num_controls)[..] { + return Err("controls must follow the local Gray-code convention.".into()); + } + if target != num_controls { + return Err("Under local numbering, target must equal num_controls.".into()); + } + + // Time order (leading CXc removed): + // [Rz(tm), C(m-1), Rz(t(m-1)), ..., C0, Rz(t0)] + let m = theta.len() - 1; + let mut circuit = Circuit::new(num_controls + 1); + circuit + .rz(Qubit::new(target as u32), theta[m]) + .map_err(|e| e.to_string())?; + for idx in (0..m).rev() { + circuit + .cx(Qubit::new(controls[idx] as u32), Qubit::new(target as u32)) + .map_err(|e| e.to_string())?; + circuit + .rz(Qubit::new(target as u32), theta[idx]) + .map_err(|e| e.to_string())?; + } + Ok(circuit) +} + +/// UCRz numeric description (mirrors the Python `dict` return value). +#[derive(Debug, Clone)] +pub struct UcrzData { + /// Target UCRz angle vector. + pub alpha: Vec, + /// Gray-expanded circuit rotation angle vector. + pub theta: Vec, + /// Gray-code sequence. + pub gray_codes: Vec, + /// Local control positions. + pub controls: Vec, + /// Gray matrix `M^k`. + pub gray_matrix: Cm, + /// Number of control qubits `k`. + pub num_controls: usize, + /// Local target qubit (equals `num_controls` under this convention). + pub target: usize, +} + +/// Turns `D` into the UCRz numeric data plus a local circuit in one step. +/// +/// Mirrors the Python `step3_ucrz_to_circuit`. +pub fn step3_ucrz_to_circuit(d: &Cm, atol: f64) -> Result { + let data = step3_ucrz_from_diagonal(d, atol)?; + let circuit = synthesize_ucrz_circuit(&data.theta, &data.controls, data.target)?; + Ok(UcrzCircuitData { data, circuit }) +} + +/// UCRz result including the circuit. +#[derive(Debug)] +pub struct UcrzCircuitData { + pub data: UcrzData, + pub circuit: Circuit, +} diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs new file mode 100644 index 00000000..386a9097 --- /dev/null +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs @@ -0,0 +1,222 @@ +// 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 optimization: two-qubit 2-CNOT + diagonal-remainder synthesis +//! (paper Sec. 5.1). +//! +//! The paper (arXiv:2403.13692 Sec. 5.1) cites the Shende-Markov-Bullock +//! "up to diagonal" technique (PRL version: quant-ph/0406176; membership +//! criterion: quant-ph/0308045, Prop. III.3): for any two-qubit unitary `v` +//! there is a (computational-basis) diagonal `d` such that both `d @ v` and +//! `v @ d` can be implemented with 2 CNOTs; the diagonal remainder commutes +//! through the surrounding gates and merges into the next two-qubit gate. +//! +//! Membership criterion (SMB Prop. III.3): `u in SU(4)` admits a 2-CNOT +//! circuit iff `tr[gamma(u)]` is real, where `gamma(u) = u @ S @ u^T @ S` +//! with `S = sigma_y (x) sigma_y`. +//! +//! Explicit closed-form construction (derived here): for a 4x4 unitary `U` +//! let `M = U @ S @ U^T` (complex symmetric), `A = M[1][2]` and +//! `B = M[0][3]` (the paired entries coincide by symmetry), `alpha = arg A`, +//! `beta = arg B`, `delta = arg det U` and `c0 = alpha + beta - delta`. Then +//! ```text +//! u* = atan2(|B| sin c0, |A| + |B| cos c0), v* = c0 - u*, +//! D = diag(1, 1, e^{i(u*-alpha)}, e^{i(v*-beta)}), +//! ``` +//! so the SU(4) normalization of `T = D @ U` satisfies `tr[gamma(T)]` real +//! (key identity: `tr[gamma(D @ U)] = 2 (d1 d2 m12 - d0 d3 m03)`; the +//! normalizing phase contributes exactly the `delta` argument to the +//! balancing equation, which is a two-phasor sum and therefore always +//! solvable), hence `T` lies in the 2-CNOT class. +//! +//! Synthesis contract (see `engine::run_a2_chain`): +//! `D_out @ circuit == target` up to global phase, where `circuit` +//! implements `T = D @ target` and `D_out = e^{i phi_T} @ D^-1` - a pure +//! diagonal phase matrix acting on qubits `(q1, q0)`. +//! +//! Migration legality: within the assembled Block-ZXZ/A.1 circuit the +//! non-leaf gates are only `Rz(top)`, `CX(ctrl < top -> top)` and `H(top)`. +//! The diagonal remainder's phase depends only on the `(q1, q0)` values and +//! therefore commutes with every such gate, so it migrates to the next +//! two-qubit leaf unchanged (entering its synthesis target as +//! `U_next @ D_out`), where it is absorbed by that leaf's own synthesis. The +//! temporally last leaf uses the full 0-3 CNOT synthesis to absorb the whole +//! accumulated remainder. + +use crate::circuit::{Circuit, Parameter, Qubit}; +use crate::compile::transform::decompose::unitary::{ + TwoQubitUnitaryDecomposeBasis, synthesize_numeric_2q_unitary, +}; +use ndarray::Array2; +use num_complex::Complex64; + +use super::matrix::{Cm, adjoint, eye, mat_mul, to_faer}; + +/// `S = sigma_y (x) sigma_y` in basis order `(q1, q0)` (the tensor's first +/// factor is the higher qubit q1). +/// +/// From `sigma_y|0> = i|1>` and `sigma_y|1> = -i|0>`: +/// `S|00> = -|11>`, `S|01> = |10>`, `S|10> = |01>`, `S|11> = -|00>`, +/// so `S = [[0,0,0,-1],[0,0,1,0],[0,1,0,0],[-1,0,0,0]]` (real, symmetric, +/// involutory, unitary). +fn syy_matrix() -> Cm { + let mut s = Array2::::zeros((4, 4)); + let one = Complex64::new(1.0, 0.0); + s[[0, 3]] = -one; + s[[1, 2]] = one; + s[[2, 1]] = one; + s[[3, 0]] = -one; + s +} + +/// Builds the left-multiplying diagonal phase `D` that puts `T = D @ U` +/// into the 2-CNOT class (the explicit solution of SMB Prop. III.3; see +/// the module documentation for the derivation). +pub fn two_cnot_phase_diagonal(u: &Cm) -> Cm { + let s = syy_matrix(); + let u_t = u.t().to_owned(); // plain transpose (no conjugation) + let m = mat_mul(&mat_mul(u, &s), &u_t); // M = U S U^T, complex symmetric + + let a = m[[1, 2]]; // by symmetry m[1][2] == m[2][1] + let b = m[[0, 3]]; // by symmetry m[0][3] == m[3][0] + let alpha = a.arg(); + let beta = b.arg(); + let r1 = a.norm(); + let r0 = b.norm(); + + // delta = arg det U. + let fm = to_faer(u); + let det = fm.determinant(); + let delta = Complex64::new(det.re, det.im).arg(); + + // Balancing equation (always solvable): + // (r1 + r0 cos c0) sin u* = r0 sin(c0) cos u*. + let c0 = alpha + beta - delta; + let u_star = (r0 * c0.sin()).atan2(r1 + r0 * c0.cos()); + let v_star = c0 - u_star; + + // Simplest assignment of the constraint d1 d2 = e^{i(u* - alpha + ...)}: + // d0 = d1 = 1. + let phi_p = u_star - alpha; + let phi_q = v_star - beta; + let mut d = eye(4); + d[[2, 2]] = Complex64::from_polar(1.0, phi_p); + d[[3, 3]] = Complex64::from_polar(1.0, phi_q); + d +} + +/// Result of the optimized synthesis of one two-qubit leaf in A.2. +pub struct TwoCnotSynthesis { + /// 2-CNOT (or fewer) circuit that implements `target` together with + /// [`diagonal_out`](Self::diagonal_out). + pub circuit: Circuit, + /// Diagonal remainder `D_out = e^{i phi_T} D^-1` acting on qubits + /// `(q1, q0)` on the temporally later side (left end of the matrix + /// product), satisfying `D_out @ circuit == target` up to global phase. + pub diagonal_out: Cm, + /// Number of CX gates actually used by this synthesis. + pub cx_count: usize, +} + +/// Decomposes `target` into a 2-CNOT circuit plus a pure diagonal remainder. +/// +/// Synthesis contract: `D_out @ circuit == target` up to global phase. The +/// remainder is a unit-modulus diagonal matrix; if `target` already lies in +/// the 2-CNOT class (e.g. local or controlled structure), or if the +/// closed-form construction unexpectedly fails numerically, the full +/// synthesis is returned with an identity remainder. +pub fn synth_two_cnot_with_diagonal(target: &Cm) -> Result { + // Baseline synthesis (3 CNOTs or fewer) - always a correct fallback. + let baseline = synthesize_for_matrix(target)?; + let baseline_cx = count_cx(&baseline.0); + if baseline_cx <= 2 { + // The target itself is already in the 2-CNOT class. + return Ok(TwoCnotSynthesis { + circuit: baseline.0, + diagonal_out: eye(4), + cx_count: baseline_cx, + }); + } + + // SMB construction: T = D @ target lies in the 2-CNOT class and the + // remainder D_out = e^{i phi_T} D^-1 is purely diagonal. + let d = two_cnot_phase_diagonal(target); + let t = mat_mul(&d, target); + let (circuit, global_phase) = synthesize_for_matrix(&t)?; + let cx = count_cx(&circuit); + if cx <= 2 { + let phase = Complex64::from_polar(1.0, global_phase); + let mut d_out = adjoint(&d); // D diagonal unitary => D^-1 = D^H + d_out.mapv_inplace(|v| v * phase); + // D_out @ circuit == e^{i phi_T} D^-1 T == D^-1 D target == target. + return Ok(TwoCnotSynthesis { + circuit, + diagonal_out: d_out, + cx_count: cx, + }); + } + + // Fallback: plain 3-CNOT synthesis (the chain breaks here but stays + // numerically correct; should not trigger under the closed form). + Ok(TwoCnotSynthesis { + circuit: baseline.0, + diagonal_out: eye(4), + cx_count: baseline_cx, + }) +} + +/// Counts `CX` gates in a circuit, including nested composite gates. +pub fn count_cx(circuit: &Circuit) -> usize { + use crate::circuit::gate::Instruction; + let mut total = 0; + for op in circuit.operations() { + match &op.instruction { + Instruction::Standard(gate) => { + if gate.name() == "CX" { + total += 1; + } + } + Instruction::CircuitGate(cg) => { + total += count_cx(cg.circuit().as_ref().circuit()); + } + _ => {} + } + } + total +} + +/// Synthesizes a 4x4 unitary on qubits `[1, 0]` in the Cx basis (consistent +/// with the whole engine); returns `(circuit, global_phase)` with +/// `e^{i phi} circuit == matrix`. +fn synthesize_for_matrix(matrix: &Cm) -> Result<(Circuit, f64), String> { + let synthesis = synthesize_numeric_2q_unitary( + matrix, + [Qubit::new(1), Qubit::new(0)], + TwoQubitUnitaryDecomposeBasis::Cx, + ) + .map_err(|e| e.to_string())?; + let mut circuit = Circuit::from_operations( + vec![Qubit::new(0), Qubit::new(1)], + synthesis.operations, + None, + None, + ) + .map_err(|e| e.to_string())?; + circuit.set_global_phase(Parameter::from(synthesis.global_phase)); + Ok((circuit, synthesis.global_phase)) +} + +/// Full (0-3 CX adaptive) synthesis for the last / unoptimized leaf. +pub fn synth_leaf_full(target: &Cm) -> Result { + let (circuit, _) = synthesize_for_matrix(target)?; + Ok(circuit) +} From 1f9982b7684590b5d0da3bc16a3bc6582193a96f Mon Sep 17 00:00:00 2001 From: Chen Xinmiao Date: Wed, 21 Oct 2026 14:20:35 +0800 Subject: [PATCH 2/4] fix lint --- .../cqlib/compile/transform/decompose/block_zxz.pyi | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi index ef09baaa..ecac40bf 100644 --- a/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi +++ b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi @@ -19,7 +19,6 @@ from numpy.typing import ArrayLike, NDArray from cqlib.circuit import Circuit - class BlockZxzDecomposeOptions: """Optimization switches of the paper's Section 5 reductions. @@ -40,14 +39,12 @@ class BlockZxzDecomposeOptions: 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: """Options with every optimization disabled (unoptimized pipeline).""" @@ -57,7 +54,6 @@ class BlockZxzDecomposeOptions: def __deepcopy__(self, memo: dict[int, object]) -> BlockZxzDecomposeOptions: ... def __eq__(self, other: object) -> bool: ... - def decompose_block_zxz(matrix: ArrayLike, atol: float = 1e-10) -> Circuit: """Decompose a general n-qubit unitary into single-qubit rotations and CX gates via the recursive Block-ZXZ method. @@ -79,7 +75,6 @@ def decompose_block_zxz(matrix: ArrayLike, atol: float = 1e-10) -> Circuit: """ ... - def decompose_block_zxz_with_options( matrix: ArrayLike, atol: float = 1e-10, @@ -107,7 +102,6 @@ def decompose_block_zxz_with_options( """ ... - def block_zxz_step1( matrix: ArrayLike, atol: float = 1e-10 ) -> tuple[ @@ -124,7 +118,6 @@ def block_zxz_step1( """ ... - def block_zxz_demux_pair( u0: ArrayLike, u1: ArrayLike, atol: float = 1e-10 ) -> tuple[ @@ -143,7 +136,6 @@ def block_zxz_demux_pair( """ ... - def block_zxz_step3_ucrz_to_circuit( d_matrix: ArrayLike, atol: float = 1e-10 ) -> Circuit: @@ -155,17 +147,14 @@ def block_zxz_step3_ucrz_to_circuit( """ ... - def block_zxz_is_block_diagonal(matrix: ArrayLike, atol: float = 1e-10) -> bool: """Return whether ``matrix`` is block-diagonal (controlled-gate shape).""" ... - def block_zxz_cx_count(circuit: Circuit) -> int: """Count the CX gates of ``circuit`` (nested composite blocks included).""" ... - __all__ = [ "BlockZxzDecomposeOptions", "decompose_block_zxz", From ffd2df04dc9e8781adfbed1f5aa5abec38fa552c Mon Sep 17 00:00:00 2001 From: Chen <17748292+chen-xinmiao1@user.noreply.gitee.com> Date: Mon, 2 Nov 2026 10:54:57 +0800 Subject: [PATCH 3/4] feat:block-zxz multi-qubit quantum gate decomposition --- crates/binding-c/src/compile/decompose.rs | 307 ++++++++++- .../compile/transform/decompose/__init__.py | 2 + .../compile/transform/decompose/__init__.pyi | 19 +- .../compile/transform/decompose/block_zxz.pyi | 22 +- .../compile/transform/decompose/block_zxz.rs | 65 ++- .../src/compile/transform/decompose/config.rs | 26 +- .../src/compile/transform/decompose/mod.rs | 2 + .../src/compile/transform/decompose/pass.rs | 6 +- .../transform/decompose/block_zxz/engine.rs | 105 +++- .../transform/decompose/block_zxz/matrix.rs | 331 ++++++++++-- .../transform/decompose/block_zxz/mod.rs | 7 + .../transform/decompose/block_zxz/step1.rs | 52 +- .../transform/decompose/block_zxz/step2.rs | 5 +- .../transform/decompose/block_zxz/vw.rs | 71 +++ .../src/compile/transform/decompose/mod.rs | 11 +- .../src/compile/transform/decompose/rule.rs | 19 + .../transform/decompose/unitary/decompose.rs | 497 +++++++++++++++++- .../transform/decompose/unitary/mod.rs | 8 +- 18 files changed, 1399 insertions(+), 156 deletions(-) diff --git a/crates/binding-c/src/compile/decompose.rs b/crates/binding-c/src/compile/decompose.rs index 143acea2..4605a2f4 100644 --- a/crates/binding-c/src/compile/decompose.rs +++ b/crates/binding-c/src/compile/decompose.rs @@ -21,6 +21,9 @@ use crate::error::CqlibError; use cqlib_core::circuit::{Instruction, ParameterValue, Qubit, StandardGate, ValueOperation}; use cqlib_core::compile::commutation::CommutationConfig; use cqlib_core::compile::resource::{ResourceLimits, ResourcePolicy}; +use cqlib_core::compile::transform::decompose::block_zxz::{ + self as core_block_zxz, DecomposeOptions as CoreBlockZxzDecomposeOptions, +}; use cqlib_core::compile::transform::decompose::mc_gate::decompose_mc_gates_for_device as core_decompose_mc_gates_for_device; use cqlib_core::compile::transform::decompose::unitary::{ KakDecomposition, TwoQubitSynthesisTarget, TwoQubitUnitaryDecomposeBasis, @@ -91,8 +94,12 @@ pub struct CDecompositionRuleStats { pub struct CUnitaryDecomposeConfig { /// 1 recurses into control-flow bodies, 0 does not. pub recurse_control_flow: u8, + /// Block-ZXZ optimization mask applied to three-or-more-qubit unitary + /// gates; a bitwise OR of `BLOCK_ZXZ_OPT_*` (see + /// `decompose_unitary_config_default` for the fully optimized default). + pub block_zxz_options: u8, /// Reserved padding to keep the struct layout stable. - pub _reserved: [u8; 7], + pub _reserved: [u8; 6], } /// C form of [`McGateDecomposeConfig`]. @@ -170,11 +177,16 @@ pub struct CTargetBasisLowerer { } /// Returns the default unitary-decompose configuration by value. +/// +/// The default enables control-flow recursion and the fully optimized +/// Block-ZXZ configuration (`BLOCK_ZXZ_OPT_ALL`) for three-or-more-qubit +/// unitary gates. #[unsafe(no_mangle)] pub extern "C" fn decompose_unitary_config_default() -> CUnitaryDecomposeConfig { CUnitaryDecomposeConfig { recurse_control_flow: 1, - _reserved: [0; 7], + block_zxz_options: BLOCK_ZXZ_OPT_ALL, + _reserved: [0; 6], } } @@ -274,6 +286,11 @@ pub extern "C" fn decompose_expand_definitions(circuit: *const CCircuit) -> *mut /// Synthesizes matrix-backed unitary gates of `circuit` and returns the /// rebuilt circuit as an owned `CCircuit*` (free with `circuit_free`). /// +/// One- and two-qubit gates use the unconstrained default synthesis +/// target; three-or-more-qubit gates go through the recursive Block-ZXZ +/// decomposition with the paper's Section 5 CNOT optimizations, selected +/// through `config.block_zxz_options`. +/// /// Returns NULL on error. #[unsafe(no_mangle)] pub extern "C" fn decompose_unitaries( @@ -287,30 +304,35 @@ pub extern "C" fn decompose_unitaries( /// pass-local rule-cache statistics to `stats` when it is non-NULL. /// /// Returns the rebuilt circuit as an owned `CCircuit*` (free with -/// `circuit_free`), or NULL on error (`stats` is then left untouched). +/// `circuit_free`), or NULL on error (`stats` is then left untouched). Any +/// internal numerical failure surfaces as NULL; the calling process is +/// never aborted. #[unsafe(no_mangle)] pub extern "C" fn decompose_unitaries_with_rule_stats( circuit: *const CCircuit, config: CUnitaryDecomposeConfig, stats: *mut CDecompositionRuleStats, ) -> *mut CCircuit { - if circuit.is_null() { - return std::ptr::null_mut(); - } - let config = UnitaryDecomposeConfig { - two_qubit_target: Default::default(), - recurse_control_flow: config.recurse_control_flow != 0, - }; - 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), - })) + catch_panic(std::ptr::null_mut(), || { + if circuit.is_null() { + return std::ptr::null_mut(); } - Err(_) => std::ptr::null_mut(), - } + let config = UnitaryDecomposeConfig { + two_qubit_target: Default::default(), + recurse_control_flow: config.recurse_control_flow != 0, + block_zxz_options: block_zxz_options_from_mask(config.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), + })) + } + Err(_) => std::ptr::null_mut(), + } + }) } /// Rewrites multi-controlled gates of `circuit` and returns the rebuilt @@ -1143,3 +1165,250 @@ pub extern "C" fn decompose_unitary_target_cost_of_fixed_operations( } CqlibError::Ok as i32 } + +// ===== Block-ZXZ decomposition ===== + +/// Hard qubit-count cap for Block-ZXZ C entry points, matching the +/// `MAX_UNITARY_QUBITS` cap of `circuit_unitary` (a 2^21 x 2^21 matrix alone +/// would need 32 TiB). +const BLOCK_ZXZ_MAX_DIM: usize = 1usize << 20; + +/// Runs `body`, mapping an unwinding panic to `fallback` (by value). +/// +/// The plain Rust extern C ABI aborts the whole process when a panic +/// tries to unwind out of the exported function, which would take down +/// any C caller on a single numerical edge case. Every Block-ZXZ entry +/// point is guarded so that a genuine bug surfaces as a NULL pointer or +/// error code instead of a process abort. +fn catch_panic T>(fallback: T, body: F) -> T { + std::panic::catch_unwind(std::panic::AssertUnwindSafe(body)).unwrap_or(fallback) +} + +/// Block-ZXZ optimization switches, combined by bitwise OR. +/// +/// The default configuration is [`BLOCK_ZXZ_OPT_ALL`] (both paper Section 5 +/// optimizations enabled). Block-diagonal (controlled-gate) inputs +/// automatically disable A.2 unless [`BLOCK_ZXZ_OPT_A2_FORCE`] is set. +/// | Value | Switch | +/// |-------|---------------------------------------------------| +/// | 0 | No optimization (unoptimized pipeline) | +/// | 1 | A.1: fold UCRz side CNOTs into the middle demux | +/// | 2 | A.2: 2-CNOT leaves + rolling diagonal remainders | +/// | 4 | Force A.2 on block-diagonal (controlled) inputs | +pub const BLOCK_ZXZ_OPT_A1: u8 = 1; +pub const BLOCK_ZXZ_OPT_A2: u8 = 2; +pub const BLOCK_ZXZ_OPT_A2_FORCE: u8 = 4; +/// A.1 + A.2 (the paper's default fully optimized configuration). +pub const BLOCK_ZXZ_OPT_ALL: u8 = BLOCK_ZXZ_OPT_A1 | BLOCK_ZXZ_OPT_A2; + +/// Converts a C option bitmask into the core [`CoreBlockZxzDecomposeOptions`]. +fn block_zxz_options_from_mask(mask: u8) -> CoreBlockZxzDecomposeOptions { + CoreBlockZxzDecomposeOptions { + opt_a1: mask & BLOCK_ZXZ_OPT_A1 != 0, + opt_a2: mask & BLOCK_ZXZ_OPT_A2 != 0, + opt_a2_force: mask & BLOCK_ZXZ_OPT_A2_FORCE != 0, + } +} + +/// Reads a row-major `dim` by `dim` complex matrix into an owned `Array2`. +/// +/// The dimension is validated before any memory is read: a non-power-of +/// two or oversized `dim` is refused instead of attempting a huge copy +/// that would exhaust memory or read out of bounds of the caller buffer. +fn block_zxz_matrix_from_c(matrix: *const Complex64, dim: usize) -> Option> { + if matrix.is_null() || dim == 0 { + return None; + } + if dim > BLOCK_ZXZ_MAX_DIM || dim & (dim - 1) != 0 { + return None; + } + let flat = unsafe { std::slice::from_raw_parts(matrix, dim * dim) }.to_vec(); + Array2::from_shape_vec((dim, dim), flat).ok() +} + +/// Runs the full Block-ZXZ decomposition of a general `2^n x 2^n` unitary +/// and returns the assembled circuit as an owned `CCircuit*` (free with +/// `circuit_free`). +/// +/// `matrix` points at `dim * dim` row-major `Complex64` elements; `dim` +/// must be a power of two >= 2 and at most 2^20. `options` is a bitwise OR +/// of `BLOCK_ZXZ_OPT_*` (pass [`BLOCK_ZXZ_OPT_ALL`] for the paper's fully +/// optimized configuration). Returns NULL on NULL input, an invalid +/// shape (including a NaN or infinite matrix), a non-unitary matrix, or an +/// internal numerical failure; the calling process is never aborted. +/// +/// Numerically degenerate inputs may use up to two extra CX: when folding +/// the accumulated A.2 diagonal remainder into a two-qubit leaf is not +/// numerically feasible, the remainder is emitted as an explicit diagonal +/// gate instead of failing. +#[unsafe(no_mangle)] +pub extern "C" fn block_zxz_decompose( + matrix: *const Complex64, + dim: usize, + atol: f64, + options: u8, +) -> *mut CCircuit { + catch_panic(std::ptr::null_mut(), || { + let Some(matrix) = block_zxz_matrix_from_c(matrix, dim) else { + return std::ptr::null_mut(); + }; + let options = block_zxz_options_from_mask(options); + match core_block_zxz::decompose_block_zxz_with_options(&matrix, atol, &options) { + Ok(result) => Box::into_raw(Box::new(CCircuit { + inner: result.circuit, + })), + Err(_) => std::ptr::null_mut(), + } + }) +} + +/// Runs Block-ZXZ step 1 and writes the four `dim/2 x dim/2` factors +/// `A1, A2, B, C` into `out_a1`, `out_a2`, `out_b`, `out_c` (each pointing +/// at `(dim/2)^2` row-major `Complex64` slots). +/// +/// Returns 0 on success, -1 on NULL arguments, -6 on an invalid input +/// matrix (including NaN or infinite elements) or an internal numerical +/// failure. The calling process is never aborted. +#[unsafe(no_mangle)] +pub extern "C" fn block_zxz_step1( + matrix: *const Complex64, + dim: usize, + atol: f64, + out_a1: *mut Complex64, + out_a2: *mut Complex64, + out_b: *mut Complex64, + out_c: *mut Complex64, +) -> i32 { + catch_panic(CqlibError::CompilerError as i32, || { + if out_a1.is_null() || out_a2.is_null() || out_b.is_null() || out_c.is_null() { + return CqlibError::NullPtr as i32; + } + let Some(matrix) = block_zxz_matrix_from_c(matrix, dim) else { + return CqlibError::NullPtr as i32; + }; + match core_block_zxz::block_zxz_step1(&matrix, atol) { + Ok((a1, a2, b, c)) => { + let half = dim / 2; + unsafe { + write_matrix_out(&a1, out_a1, half); + write_matrix_out(&a2, out_a2, half); + write_matrix_out(&b, out_b, half); + write_matrix_out(&c, out_c, half); + } + CqlibError::Ok as i32 + } + Err(_) => CqlibError::CompilerError as i32, + } + }) +} + +/// Copies an owned square matrix into a caller-provided row-major buffer. +/// +/// # Safety +/// +/// `out` must point at `dim * dim` writable `Complex64` slots. +unsafe fn write_matrix_out(matrix: &Array2, out: *mut Complex64, dim: usize) { + let slice = unsafe { std::slice::from_raw_parts_mut(out, dim * dim) }; + for (slot, value) in slice.iter_mut().zip(matrix.iter()) { + *slot = *value; + } +} + +/// Demultiplexes a block pair into the factors `V, D, W` and writes them +/// into `out_v`, `out_d`, `out_w` (each `dim x dim` row-major slots). +/// +/// The factors satisfy `U0 = V D W` and `U1 = V D† W`. Returns 0 on +/// success, -1 on NULL arguments, -6 on invalid inputs (including NaN or +/// infinite elements) or an internal numerical failure. The calling process +/// is never aborted. +#[unsafe(no_mangle)] +pub extern "C" fn block_zxz_demux_pair( + u0: *const Complex64, + u1: *const Complex64, + dim: usize, + atol: f64, + out_v: *mut Complex64, + out_d: *mut Complex64, + out_w: *mut Complex64, +) -> i32 { + catch_panic(CqlibError::CompilerError as i32, || { + if out_v.is_null() || out_d.is_null() || out_w.is_null() { + return CqlibError::NullPtr as i32; + } + let (Some(u0), Some(u1)) = ( + block_zxz_matrix_from_c(u0, dim), + block_zxz_matrix_from_c(u1, dim), + ) else { + return CqlibError::NullPtr as i32; + }; + match core_block_zxz::step2::demux_pair(&u0, &u1, atol) { + Ok((v, d, w)) => { + unsafe { + write_matrix_out(&v, out_v, dim); + write_matrix_out(&d, out_d, dim); + write_matrix_out(&w, out_w, dim); + } + CqlibError::Ok as i32 + } + Err(_) => CqlibError::CompilerError as i32, + } + }) +} + +/// Expands a `dim x dim` diagonal unitary `D` into its uniformly controlled +/// `Rz` circuit and returns it as an owned `CCircuit*` (free with +/// `circuit_free`). +/// +/// The returned circuit enacts `diag(D, D†)` on `log2(2*dim)` qubits with +/// the local Gray-code control convention. Returns NULL on NULL input or a +/// non-diagonal / non-unitary matrix (including NaN or infinite elements). +/// The calling process is never aborted. +#[unsafe(no_mangle)] +pub extern "C" fn block_zxz_ucrz_circuit( + d_matrix: *const Complex64, + dim: usize, + atol: f64, +) -> *mut CCircuit { + catch_panic(std::ptr::null_mut(), || { + let Some(d_matrix) = block_zxz_matrix_from_c(d_matrix, dim) else { + return std::ptr::null_mut(); + }; + match core_block_zxz::ucrz::step3_ucrz_to_circuit(&d_matrix, atol) { + Ok(result) => Box::into_raw(Box::new(CCircuit { + inner: result.circuit, + })), + Err(_) => std::ptr::null_mut(), + } + }) +} + +/// Returns the number of `CX` gates in `circuit` (including nested +/// composite-gate blocks), or 0 for NULL. A guard failure also reports 0; +/// the calling process is never aborted. +#[unsafe(no_mangle)] +pub extern "C" fn block_zxz_cx_count(circuit: *const CCircuit) -> usize { + if circuit.is_null() { + return 0; + } + catch_panic(0, || { + core_block_zxz::vw::count_cx(unsafe { &(*circuit).inner }) + }) +} + +/// Returns 1 when `matrix` is block-diagonal (a controlled-gate shape) +/// within `atol`, 0 when it is not (including NaN or infinite elements in +/// the off-diagonal blocks), -1 on NULL input, and -6 when the input cannot +/// be evaluated. The calling process is never aborted. +#[unsafe(no_mangle)] +pub extern "C" fn block_zxz_is_block_diagonal( + matrix: *const Complex64, + dim: usize, + atol: f64, +) -> i32 { + catch_panic(CqlibError::CompilerError as i32, || { + let Some(matrix) = block_zxz_matrix_from_c(matrix, dim) else { + return CqlibError::NullPtr as i32; + }; + core_block_zxz::engine::is_block_diagonal(&matrix, atol) as i32 + }) +} diff --git a/crates/binding-python/cqlib/compile/transform/decompose/__init__.py b/crates/binding-python/cqlib/compile/transform/decompose/__init__.py index 779d2cde..120a64e2 100644 --- a/crates/binding-python/cqlib/compile/transform/decompose/__init__.py +++ b/crates/binding-python/cqlib/compile/transform/decompose/__init__.py @@ -29,6 +29,7 @@ """ 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 @@ -50,6 +51,7 @@ decompose_mc_gates_for_device = _decompose_module.decompose_mc_gates_for_device __all__ = [ + "block_zxz", "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..895c776d 100644 --- a/crates/binding-python/cqlib/compile/transform/decompose/__init__.pyi +++ b/crates/binding-python/cqlib/compile/transform/decompose/__init__.pyi @@ -14,8 +14,10 @@ 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 class TwoQubitUnitaryDecomposeBasis: """Output interaction basis for numeric two-qubit unitary synthesis.""" @@ -56,6 +58,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 +80,14 @@ class UnitaryDecomposeConfig: def recurse_control_flow(self) -> bool: """Whether unitary gates in control-flow bodies are synthesized.""" ... + @property + def block_zxz_options(self) -> BlockZxzDecomposeOptions | None: + """Block-ZXZ switches applied to three-or-more-qubit unitary gates. + + ``None`` keeps the defaults: both paper Section 5 optimizations + enabled. + """ + ... def __copy__(self) -> UnitaryDecomposeConfig: ... def __deepcopy__(self, memo: dict[int, object]) -> UnitaryDecomposeConfig: ... def __eq__(self, other: object) -> bool: ... @@ -135,7 +146,12 @@ def decompose_unitaries( circuit: Circuit, config: UnitaryDecomposeConfig | None = None, ) -> TransformResult: - """Synthesize matrix-backed one- and two-qubit unitary gates. + """Synthesize matrix-backed unitary gates. + + One- and two-qubit gates use the configured synthesis targets; + three-or-more-qubit gates are synthesized through the recursive + Block-ZXZ decomposition (paper arXiv:2403.13692) with the paper's + Section 5 CNOT optimizations. Raises: CompilerConfigError: If a unitary is unresolved, invalid, or @@ -186,6 +202,7 @@ def decompose_mc_gates_for_device( ... __all__ = [ + "block_zxz", "mc_gate", "unitary", "TwoQubitUnitaryDecomposeBasis", diff --git a/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi index ecac40bf..67896f95 100644 --- a/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi +++ b/crates/binding-python/cqlib/compile/transform/decompose/block_zxz.pyi @@ -62,16 +62,24 @@ def decompose_block_zxz(matrix: ArrayLike, atol: float = 1e-10) -> Circuit: the CNOT count meets the paper bound ``22/48 * 4^n - 3/2 * 2^n + 5/3`` (n=3 -> 19, n=4 -> 95). + Numerically degenerate inputs can exceed that bound by at most two CX: + when folding the accumulated A.2 diagonal remainder into a two-qubit + leaf is not numerically feasible, the remainder is emitted as an + explicit diagonal gate instead of failing the decomposition. + Args: matrix: Square power-of-two unitary matrix. - atol: Absolute tolerance of the unitarity and invariant checks. + atol: Absolute tolerance of the unitarity and invariant checks; + must be a finite non-negative number. Returns: The assembled :class:`~cqlib.circuit.Circuit`. Raises: - ValueError: If ``matrix`` is not a square power-of-two unitary or a - decomposition invariant fails. + ValueError: If ``matrix`` is not a square power-of-two unitary (a + NaN or infinite entry is rejected up front), if ``atol`` is + not a finite non-negative number, or if a decomposition + invariant fails. """ ... @@ -89,7 +97,8 @@ def decompose_block_zxz_with_options( Args: matrix: Square power-of-two unitary matrix. - atol: Absolute tolerance of the unitarity and invariant checks. + atol: Absolute tolerance of the unitarity and invariant checks; + must be a finite non-negative number. options: Optimization switches; ``None`` selects the fully optimized default. @@ -97,8 +106,9 @@ def decompose_block_zxz_with_options( The assembled :class:`~cqlib.circuit.Circuit`. Raises: - ValueError: If ``matrix`` is invalid or a decomposition invariant - fails. + ValueError: If ``matrix`` is invalid (including NaN or infinite + entries), if ``atol`` is not a finite non-negative number, or + if a decomposition invariant fails. """ ... diff --git a/crates/binding-python/src/compile/transform/decompose/block_zxz.rs b/crates/binding-python/src/compile/transform/decompose/block_zxz.rs index 9987463a..6cd262a8 100644 --- a/crates/binding-python/src/compile/transform/decompose/block_zxz.rs +++ b/crates/binding-python/src/compile/transform/decompose/block_zxz.rs @@ -26,6 +26,21 @@ use numpy::{PyArray2, PyArrayMethods}; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; +/// The four factor matrices returned by `block_zxz_step1`. +type Step1Arrays<'py> = ( + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, +); + +/// The three factor matrices returned by `block_zxz_demux_pair`. +type DemuxArrays<'py> = ( + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, + Bound<'py, PyArray2>, +); + /// Optimization switches of the paper's Section 5 reductions. /// /// ``opt_a1`` (paper 5.2 / Eq. 11) folds each recursion level's two UCRz @@ -88,13 +103,7 @@ impl PyBlockZxzDecomposeOptions { } fn __repr__(&self) -> String { - let opt = |value: bool| if value { "True" } else { "False" }; - format!( - "BlockZxzDecomposeOptions(opt_a1={}, opt_a2={}, opt_a2_force={})", - opt(self.inner.opt_a1), - opt(self.inner.opt_a2), - opt(self.inner.opt_a2_force) - ) + self.repr_string() } fn __eq__(&self, other: &Self) -> bool { @@ -112,6 +121,19 @@ impl PyBlockZxzDecomposeOptions { } } +impl PyBlockZxzDecomposeOptions { + /// Formats the options for Python reprs. + pub(crate) fn repr_string(&self) -> String { + let opt = |value: bool| if value { "True" } else { "False" }; + format!( + "BlockZxzDecomposeOptions(opt_a1={}, opt_a2={}, opt_a2_force={})", + opt(self.inner.opt_a1), + opt(self.inner.opt_a2), + opt(self.inner.opt_a2_force) + ) + } +} + /// Converts the engine's `String` error into a Python `ValueError` (the /// original Python project raises `ValueError` on invalid inputs). fn string_error_to_py_err(message: String) -> pyo3::PyErr { @@ -143,9 +165,16 @@ fn circuit_into_py(circuit: Circuit) -> PyCircuit { /// the resulting CNOT count meets the paper bound /// ``22/48 * 4^n - 3/2 * 2^n + 5/3`` (n=3 -> 19, n=4 -> 95). /// +/// Numerically degenerate inputs can exceed that bound by at most two CX: +/// when folding the accumulated A.2 diagonal remainder into a two-qubit leaf +/// is not numerically feasible, the remainder is emitted as an explicit +/// diagonal gate instead of failing the decomposition. +/// /// Raises: -/// ValueError: If ``matrix`` is not a square power-of-two unitary or a -/// decomposition invariant fails. +/// ValueError: If ``matrix`` is not a square power-of-two unitary (a +/// NaN or infinite entry is rejected up front), if ``atol`` is +/// not a finite non-negative number, or if a decomposition +/// invariant fails. #[pyfunction(name = "decompose_block_zxz")] #[pyo3(signature = (matrix, atol=1e-10))] pub fn py_decompose_block_zxz( @@ -166,8 +195,9 @@ pub fn py_decompose_block_zxz( /// ``options.opt_a2_force`` is set (paper Sec. 6.2 constraint). /// /// Raises: -/// ValueError: If ``matrix`` is invalid or a decomposition invariant -/// fails. +/// ValueError: If ``matrix`` is invalid (including NaN or infinite +/// entries), if ``atol`` is not a finite non-negative number, or +/// if a decomposition invariant fails. #[pyfunction(name = "decompose_block_zxz_with_options")] #[pyo3(signature = (matrix, atol=1e-10, *, options=None))] pub fn py_decompose_block_zxz_with_options( @@ -195,12 +225,7 @@ pub fn py_block_zxz_step1<'py>( py: Python<'py>, matrix: Bound<'_, PyAny>, atol: f64, -) -> PyResult<( - Bound<'py, PyArray2>, - Bound<'py, PyArray2>, - Bound<'py, PyArray2>, - Bound<'py, PyArray2>, -)> { +) -> PyResult> { let matrix = extract_complex_matrix(py, matrix)?; let (a1, a2, b, c) = py .detach(move || { @@ -228,11 +253,7 @@ pub fn py_block_zxz_demux_pair<'py>( u0: Bound<'_, PyAny>, u1: Bound<'_, PyAny>, atol: f64, -) -> PyResult<( - Bound<'py, PyArray2>, - Bound<'py, PyArray2>, - Bound<'py, PyArray2>, -)> { +) -> PyResult> { let u0 = extract_complex_matrix(py, u0)?; let u1 = extract_complex_matrix(py, u1)?; let (v, d, w) = py diff --git a/crates/binding-python/src/compile/transform/decompose/config.rs b/crates/binding-python/src/compile/transform/decompose/config.rs index 16d212ad..aefea860 100644 --- a/crates/binding-python/src/compile/transform/decompose/config.rs +++ b/crates/binding-python/src/compile/transform/decompose/config.rs @@ -23,6 +23,8 @@ use cqlib_core::compile::transform::decompose::unitary::{ use cqlib_core::compile::transform::decompose::{McGateDecomposeConfig, UnitaryDecomposeConfig}; use pyo3::prelude::*; +use super::block_zxz::PyBlockZxzDecomposeOptions; + /// Output interaction basis used for numeric two-qubit unitary synthesis. #[pyclass( name = "TwoQubitUnitaryDecomposeBasis", @@ -118,17 +120,19 @@ pub struct PyUnitaryDecomposeConfig { pub(crate) inner: UnitaryDecomposeConfig, two_qubit_basis: Option, target_basis: Option>, + block_zxz_options: Option, } #[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( @@ -161,9 +165,13 @@ impl PyUnitaryDecomposeConfig { inner: UnitaryDecomposeConfig { two_qubit_target, recurse_control_flow, + block_zxz_options: block_zxz_options + .map(|options| options.inner) + .unwrap_or_default(), }, two_qubit_basis, target_basis, + block_zxz_options, }) } @@ -184,21 +192,33 @@ impl PyUnitaryDecomposeConfig { self.inner.recurse_control_flow } + /// Block-ZXZ optimization switches applied when synthesizing gates on + /// three or more qubits (`None` keeps the defaults: both paper Section 5 + /// optimizations enabled). + #[getter] + fn block_zxz_options(&self) -> Option { + self.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); + let block_zxz_options = self + .block_zxz_options + .map_or_else(|| "None".to_string(), |options| options.repr_string()); format!( - "UnitaryDecomposeConfig(two_qubit_basis={}, target_basis={}, recurse_control_flow={})", + "UnitaryDecomposeConfig(two_qubit_basis={}, target_basis={}, recurse_control_flow={}, block_zxz_options={})", two_qubit_basis, target_basis, if self.inner.recurse_control_flow { "True" } else { "False" - } + }, + block_zxz_options, ) } diff --git a/crates/binding-python/src/compile/transform/decompose/mod.rs b/crates/binding-python/src/compile/transform/decompose/mod.rs index 07405723..8b863981 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; @@ -49,6 +50,7 @@ pub(crate) fn register_decompose_module(parent: &Bound<'_, PyModule>) -> PyResul unitary::register_unitary_module(&m)?; mc_gate::register_mc_gate_module(&m)?; + block_zxz::register_block_zxz_module(&m)?; parent.add_submodule(&m)?; parent diff --git a/crates/binding-python/src/compile/transform/decompose/pass.rs b/crates/binding-python/src/compile/transform/decompose/pass.rs index 648c6c91..a2b7ad27 100644 --- a/crates/binding-python/src/compile/transform/decompose/pass.rs +++ b/crates/binding-python/src/compile/transform/decompose/pass.rs @@ -40,7 +40,11 @@ pub fn py_expand_definitions( .map_err(compiler_error_to_py_err) } -/// Synthesizes matrix-backed one- and two-qubit unitary gates. +/// Synthesizes matrix-backed unitary gates. +/// +/// One- and two-qubit gates use the configured synthesis targets; +/// three-or-more-qubit gates go through the recursive Block-ZXZ +/// decomposition with the paper's Section 5 CNOT optimizations. #[pyfunction(name = "decompose_unitaries")] #[pyo3(signature = (circuit, config=None))] pub fn py_decompose_unitaries( diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs index 4a2b6936..6fda44d1 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/engine.rs @@ -47,11 +47,11 @@ use super::ucrz::{ step3_ucrz_from_diagonal, synthesize_ucrz_circuit, synthesize_ucrz_circuit_reduced_tail, synthesize_ucrz_circuit_reversed_reduced_head, }; -use super::vw::{synth_leaf_full, synth_two_cnot_with_diagonal}; +use super::vw::{diagonal_gate_circuit, synth_leaf_full, synth_two_cnot_with_diagonal}; /// Decomposition options (the optimization switches of the paper's /// Section 5). -#[derive(Debug, Clone, Copy)] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct DecomposeOptions { /// A.1: fold each recursion level's two UCRz side CNOTs into the middle /// multiplexer (saves 2 CNOTs per level). @@ -92,12 +92,19 @@ fn num_qubits_of(unitary: &Array2) -> usize { } /// A node of the recursive decomposition tree. +/// +/// `RecursiveNode` is boxed because a flat inline layout would inflate every +/// `Node` to ~1.1 KB, including the far more numerous leaves (there are +/// `4^(n-2)` of them). `BaseNode` is deliberately kept inline: leaves are the +/// most common nodes in the tree, so giving each one a heap allocation would +/// cost more than the extra `Node` width it saves. +#[allow(clippy::large_enum_variant)] #[derive(Debug)] pub enum Node { /// A 1/2-qubit leaf. Base(BaseNode), /// A recursion-layer node. - Recursive(RecursiveNode), + Recursive(Box), } /// A leaf node (the matrix is cached during construction; under A.2 the @@ -173,15 +180,20 @@ pub fn get_layer_assembly_plan() -> Vec { } /// Returns whether `unitary` is block-diagonal (a controlled-gate shape, -/// the disable condition for A.2). +/// the disable condition for A.2). A non-finite off-diagonal element +/// counts as "not block-diagonal" (NaN comparisons are always false and +/// would otherwise make a broken matrix pass the `> atol` test). pub fn is_block_diagonal(unitary: &Cm, atol: f64) -> bool { let n = unitary.nrows(); let half = n / 2; for i in 0..n { for j in 0..n { let in_offdiag = (i < half) != (j < half); - if in_offdiag && unitary[[i, j]].norm() > atol { - return false; + if in_offdiag { + let m = unitary[[i, j]].norm(); + if !m.is_finite() || m > atol { + return false; + } } } } @@ -356,12 +368,12 @@ pub fn build_block_zxz_tree( for (name, sub) in &layer.subunitaries { children.push((*name, build_block_zxz_tree(sub, atol, options)?)); } - Ok(Node::Recursive(RecursiveNode { + Ok(Node::Recursive(Box::new(RecursiveNode { num_qubits: num_qubits_of(unitary), input_unitary: unitary.clone(), layer, children, - })) + }))) } /// Snapshots all two-qubit leaf matrices in circuit execution order @@ -395,6 +407,17 @@ fn collect_2q_leaf_matrices(node: &Node, out: &mut Vec) { /// the next leaf's input unchanged. The temporally last leaf uses the full /// 0-3 CX adaptive synthesis to absorb the whole accumulated remainder /// chain. +/// +/// Both absorptions can be numerically infeasible: folding a diagonal into a +/// near-degenerate leaf routinely places the target on a Weyl-chamber +/// boundary (`c -> 0`), where the shared two-qubit backend's KAK +/// canonicalization is accurate to about `1e-10` only - while that backend +/// validates candidates at `1e-10` (`RECONSTRUCTION_EPS` of the KAK module +/// itself is `1e-7`). Rather than failing the whole decomposition, the chain +/// then degrades: the leaf is synthesized unchanged and the pending +/// remainder is emitted as an explicit diagonal gate +/// ([`diagonal_gate_circuit`]) at the same position, which is exact by +/// construction at the cost of two extra CX. fn run_a2_chain(matrices: &[Cm]) -> Result, String> { use super::matrix::mat_mul; @@ -407,23 +430,63 @@ fn run_a2_chain(matrices: &[Cm]) -> Result, String> { for (index, unitary) in matrices.iter().enumerate() { let is_last = index + 1 == matrices.len(); - let target = if is_identity_diagonal(&pending) { - unitary.clone() - } else { + let has_pending = !is_identity_diagonal(&pending); + let target = if has_pending { mat_mul(unitary, &pending) + } else { + unitary.clone() }; if is_last { - circuits.push(synth_leaf_full(&target)?); - } else { - let synthesis = synth_two_cnot_with_diagonal(&target)?; - circuits.push(synthesis.circuit); - pending = synthesis.diagonal_out; + match synth_leaf_full(&target) { + Ok(circuit) => circuits.push(circuit), + Err(_) if has_pending => { + // Degraded path: emit the remainder explicitly before the + // leaf (`U_last @ D_pending` applies the remainder first) + // and synthesize the leaf unchanged. + let mut circuit = diagonal_gate_circuit(&pending)?; + let leaf = synth_leaf_full(unitary)?; + circuit.compose(&leaf, None).map_err(|e| e.to_string())?; + circuits.push(circuit); + } + Err(error) => return Err(error), + } + continue; } + + let synthesis = match synth_two_cnot_with_diagonal(&target) { + Ok(synthesis) => TwoCnotChainStep { + circuit: synthesis.circuit, + diagonal_out: synthesis.diagonal_out, + }, + Err(_) if has_pending => { + // Degraded path: emit the remainder explicitly before the + // leaf and synthesize the leaf unchanged. + let mut circuit = diagonal_gate_circuit(&pending)?; + let synthesis = synth_two_cnot_with_diagonal(unitary)?; + circuit + .compose(&synthesis.circuit, None) + .map_err(|e| e.to_string())?; + TwoCnotChainStep { + circuit, + diagonal_out: synthesis.diagonal_out, + } + } + Err(error) => return Err(error), + }; + circuits.push(synthesis.circuit); + pending = synthesis.diagonal_out; } Ok(circuits) } +/// One normalized chain step: the emitted circuit plus the diagonal that +/// must be transferred to the next leaf. +struct TwoCnotChainStep { + circuit: Circuit, + diagonal_out: Cm, +} + /// The 4x4 identity diagonal. fn identity_diagonal() -> Cm { Array2::eye(4) @@ -448,11 +511,11 @@ fn write_back_leaf_circuits( ) -> Result<(), String> { match node { Node::Base(b) => { - if b.num_qubits == 2 { - if let Some(circuit) = circuits.next() { - b.circuit = circuit; - b.method = "2q"; - } + if b.num_qubits == 2 + && let Some(circuit) = circuits.next() + { + b.circuit = circuit; + b.method = "2q"; } Ok(()) } diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs index 15b0087a..a60da414 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/matrix.rs @@ -62,10 +62,19 @@ pub fn block_diag(top_left: &Cm, bottom_right: &Cm) -> Cm { } /// Maximum elementwise absolute difference (used for allclose checks). +/// +/// A non-finite difference (caused by NaN or infinite inputs, or by a +/// numerically failed intermediate) is reported as positive infinity so +/// every allclose-style consumer rejects the matrix instead of silently +/// accepting it (`NaN > max` is always false, which would otherwise make a +/// NaN matrix look "equal"). pub fn max_abs_diff(a: &Cm, b: &Cm) -> f64 { let mut m = 0.0f64; for ((i, j), &av) in a.indexed_iter() { let d = (av - b[[i, j]]).norm(); + if !d.is_finite() { + return f64::INFINITY; + } if d > m { m = d; } @@ -83,12 +92,17 @@ pub fn is_unitary(a: &Cm, atol: f64) -> bool { } /// Returns whether `A` is diagonal within the `atol` tolerance. +/// +/// A non-finite off-diagonal element counts as "not diagonal". pub fn is_diagonal(a: &Cm, atol: f64) -> bool { let (r, c) = a.dim(); for i in 0..r { for j in 0..c { - if i != j && a[[i, j]].norm() > atol { - return false; + if i != j { + let m = a[[i, j]].norm(); + if !m.is_finite() || m > atol { + return false; + } } } } @@ -114,17 +128,31 @@ pub fn from_faer(m: &faer::MatRef<'_, Complex64>) -> Cm { /// `matrix ~ S @ U_polar`. /// /// Mirrors the Python `polar_from_svd`: `X = U Sigma V^H`, -/// `S = U Sigma U^H`, `U_polar = U V^H`. -pub fn polar_from_svd(matrix: &Cm) -> (Cm, Cm) { +/// `S = U Sigma U^H`, `U_polar = U V^H`. Numeric failures of the +/// underlying SVD (for example on non-finite inputs) are returned as +/// errors instead of panicking. +pub fn polar_from_svd(matrix: &Cm) -> Result<(Cm, Cm), String> { let fm = to_faer(matrix); - let svd = fm.svd().expect("SVD failed"); + let svd = fm.svd().map_err(|_| { + format!( + "SVD failed on a {}x{} matrix", + matrix.nrows(), + matrix.ncols() + ) + })?; let u = from_faer(&svd.U()); let v = from_faer(&svd.V()); - let s_vals: Vec = fm.singular_values().expect("singular values failed"); + let s_vals: Vec = fm.singular_values().map_err(|_| { + format!( + "singular values failed on a {}x{} matrix", + matrix.nrows(), + matrix.ncols() + ) + })?; let sigma = diagonal_from_real(&s_vals); let s_factor = mat_mul(&mat_mul(&u, &sigma), &adjoint(&u)); let u_polar = mat_mul(&u, &adjoint(&v)); - (s_factor, u_polar) + Ok((s_factor, u_polar)) } /// Eigen (Schur-style) diagonalization of a complex unitary matrix. @@ -136,33 +164,203 @@ pub fn polar_from_svd(matrix: &Cm) -> (Cm, Cm) { /// Degenerate-spectrum repair: faer's complex EVD does not guarantee that /// eigenvectors of a repeated eigenvalue are mutually orthogonal (a normal /// matrix is theoretically unitarily diagonalizable). Columns are grouped -/// by eigenvalue clusters and re-orthonormalized within each group by a -/// modified Gram-Schmidt pass; an orthonormal basis of a degenerate -/// subspace still spans the same eigenspace, so the diagonalization -/// property is preserved, and subspaces of distinct eigenvalues stay -/// (numerically) orthogonal by normality. -pub fn schur_unitary_diagonalize(matrix: &Cm) -> (Cm, Cm) { +/// by eigenvalue clusters and re-orthonormalized within each group: a +/// modified Gram-Schmidt pass first, and when the raw eigenvectors turn out +/// numerically linearly dependent (a maximally degenerate cluster), an +/// orthonormal basis of the cluster's approximate eigenspace is recovered +/// from the SVD null space of `matrix - lambda_bar I`. Both repairs keep +/// the diagonalization error bounded by the cluster/gap tolerance. +/// +/// A `matrix` that is numerically a scalar multiple of the identity is +/// diagonalized directly by the identity basis (any orthonormal basis +/// diagonalizes it); this fast path avoids running an EVD on a maximally +/// degenerate spectrum and is exact to within `atol`. +/// +/// When the EVD basis is not orthogonal enough for `atol` (LAPACK-style +/// EVD eigenvector error scales with `eps / spectral_gap`, which exceeds a +/// tight `atol` for nearly degenerate spectra), the EVD result is discarded +/// and a Jacobi (rotation) diagonalization takes over: its accumulated +/// basis is unitary by construction, independent of the spectral gap. +/// +/// Numeric failures of the underlying EVD/SVD (for example on non-finite +/// inputs) are returned as errors instead of panicking. +pub fn schur_unitary_diagonalize(matrix: &Cm, atol: f64) -> Result<(Cm, Cm), String> { + let n = matrix.nrows(); + if n > 0 && matrix.ncols() == n { + // Fast path: numerically scalar multiple of the identity. + let mu = (0..n).map(|i| matrix[[i, i]]).sum::() / n as f64; + let mut scalar = eye(n); + for i in 0..n { + scalar[[i, i]] = mu; + } + if max_abs_diff(matrix, &scalar) <= atol { + return Ok((eye(n), scalar)); + } + } + let fm = to_faer(matrix); - let eig = fm.eigen().expect("EVD failed"); + let eig = fm.eigen().map_err(|_| { + format!( + "EVD failed on a {}x{} matrix", + matrix.nrows(), + matrix.ncols() + ) + })?; let q_raw = from_faer(&eig.U()); - let evals: Vec = fm.eigenvalues().expect("eigenvalues failed"); - let q = reorthogonalize_degenerate_eigenvectors(&q_raw, &evals); + let evals: Vec = fm.eigenvalues().map_err(|_| { + format!( + "eigenvalues failed on a {}x{} matrix", + matrix.nrows(), + matrix.ncols() + ) + })?; + let q = reorthogonalize_degenerate_eigenvectors(matrix, &q_raw, &evals)?; + + // EVD eigenvector orthogonality error grows like eps / spectral_gap; + // for nearly degenerate spectra it can exceed a tight atol. In that + // case the basis is unusable (the demux factor check would reject it), + // so restart from the Jacobi iteration, which stays unitary by + // construction. + let orthogonality_error = max_abs_diff(&mat_mul(&adjoint(&q), &q), &eye(n)); + if orthogonality_error <= atol * 0.5 { + let d = diagonal_from_values(&evals); + return Ok((q, d)); + } + jacobi_diagonalize(matrix, atol) +} + +/// Jacobi (rotation) unitary diagonalization of a normal matrix. +/// +/// Sweeps through all `(p, q)` pairs and applies the analytic eigendecomposition +/// of each `2x2` sub-block as a unitary similarity transform. The accumulated +/// basis `Q` is a product of unitary transforms and therefore unitary by +/// construction, to working precision — unlike an EVD basis, whose columns +/// lose orthogonality as `eps / spectral_gap` grows. This is the numerically +/// stable path for nearly degenerate (near-scalar) spectra. +/// +/// Convergence is checked on the off-diagonal Frobenius norm; a unitary +/// matrix is normal, so the iteration converges globally for every spectrum. +fn jacobi_diagonalize(matrix: &Cm, atol: f64) -> Result<(Cm, Cm), String> { + let n = matrix.nrows(); + if n == 0 || matrix.ncols() != n { + return Err("Jacobi diagonalization requires a non-empty square matrix".into()); + } + let scale = matrix + .iter() + .map(|z| z.norm()) + .fold(0.0f64, f64::max) + .max(1.0); + // Numerical floor of the sweep target; the similarity transforms keep + // the basis unitary, so a tight target is safe. + let target = (atol * 0.05).clamp(1e-15, 1e-12) * scale; + let max_sweeps = 80; + + let mut a = matrix.clone(); + let mut q = eye(n); + for _sweep in 0..max_sweeps { + // Paardekooper: the squared Frobenius norm of the strict lower + // triangle is monotonically non-increasing under these 2x2 Schur + // transforms for a normal matrix, and converges to zero. + let mut lower_sq = 0.0f64; + for p in 0..n { + for r in (p + 1)..n { + lower_sq += a[[r, p]].norm_sqr(); + } + } + if lower_sq.sqrt() <= target { + break; + } + for p in 0..n { + for r in (p + 1)..n { + let b = a[[p, r]]; + let c = a[[r, p]]; + if c.norm() <= target * 0.01 { + continue; + } + let app = a[[p, p]]; + let aqq = a[[r, r]]; + // Analytic eigendecomposition of the 2x2 sub-block. Its + // first column is an eigenvector, so the unitary + // S = [v1, orthonormal complement] puts S^H G S into + // upper-triangular form with an exact zero at (r, p). + let half_trace = (app + aqq) * 0.5; + let half_diff = (app - aqq) * 0.5; + let disc = (half_diff * half_diff + b * c).sqrt(); + let lambda = half_trace + disc; + // Try the first row equation (a - l) x + b y = 0 first, + // fall back to the second row when its coefficients vanish + // (for example b == 0 with c != 0, which would otherwise + // collapse the vector and leave (r, p) un-zeroed). + let mut v1 = [b, lambda - app]; + let mut norm = (v1[0].norm_sqr() + v1[1].norm_sqr()).sqrt(); + if norm <= 1e-14 { + v1 = [lambda - aqq, c]; + norm = (v1[0].norm_sqr() + v1[1].norm_sqr()).sqrt(); + } + if norm <= 1e-14 { + continue; // Sub-block is already (numerically) diagonal. + } + v1[0] /= norm; + v1[1] /= norm; + // Second column of the unitary S: the orthonormal + // complement, which is the eigenvector of the other + // eigenvalue for a normal 2x2 block. + let s00 = v1[0]; + let s10 = v1[1]; + let s01 = -v1[1].conj(); + let s11 = v1[0].conj(); + // a <- S^H a (rows p, r) + for j in 0..n { + let ap = a[[p, j]]; + let ar = a[[r, j]]; + a[[p, j]] = s00.conj() * ap + s10.conj() * ar; + a[[r, j]] = s01.conj() * ap + s11.conj() * ar; + } + // a <- a S (columns p, r) + for i in 0..n { + let bp = a[[i, p]]; + let br = a[[i, r]]; + a[[i, p]] = bp * s00 + br * s10; + a[[i, r]] = bp * s01 + br * s11; + } + // q <- q S + for i in 0..n { + let qp = q[[i, p]]; + let qr = q[[i, r]]; + q[[i, p]] = qp * s00 + qr * s10; + q[[i, r]] = qp * s01 + qr * s11; + } + } + } + } + + let evals: Vec = (0..n).map(|i| a[[i, i]]).collect(); let d = diagonal_from_values(&evals); - (q, d) + Ok((q, d)) } /// Re-orthonormalizes eigenvectors inside degenerate subspaces (see the /// documentation of [`schur_unitary_diagonalize`]). /// -/// Eigenvectors of the same eigenvalue cluster are processed by a modified -/// Gram-Schmidt pass over the complex inner product; orthogonality across -/// clusters is naturally preserved by the spectral property of normal -/// matrices. Exact degeneracies on the unit circle jitter at the `~1e-15` -/// level in floating point while distinct eigenvalues are usually separated -/// by `O(0.1)`, so a `1e-7` clustering tolerance is safe. The function does -/// not move any eigenvector out of its eigenspace, so `M = Q D Q^H` still -/// holds. -fn reorthogonalize_degenerate_eigenvectors(q: &Cm, evals: &[Complex64]) -> Cm { +/// Eigenvectors of the same eigenvalue cluster are first processed by a +/// modified Gram-Schmidt pass over the complex inner product. When the raw +/// eigenvectors of a cluster are numerically linearly dependent (faer +/// returns near-collinear vectors for a repeated eigenvalue), the partial +/// Gram-Schmidt basis is discarded and an orthonormal basis of the +/// cluster's approximate eigenspace is recovered from the smallest right +/// singular vectors of `matrix - lambda_bar I`, where `lambda_bar` is the +/// cluster mean. That null-space basis is exactly the eigenspace when the +/// degeneracy is exact, and its residual is bounded by the cluster spread +/// otherwise. Orthogonality across clusters follows from the normality of +/// a unitary matrix. +/// +/// The function never produces un-orthonormalized columns, so `Q` stays +/// unitary (a demux factor check would otherwise reject it). +fn reorthogonalize_degenerate_eigenvectors( + matrix: &Cm, + q: &Cm, + evals: &[Complex64], +) -> Result { let n = q.ncols(); debug_assert_eq!(q.nrows(), n); debug_assert_eq!(evals.len(), n); @@ -191,30 +389,77 @@ fn reorthogonalize_degenerate_eigenvectors(q: &Cm, evals: &[Complex64]) -> Cm { if group.len() <= 1 { continue; } - // Modified Gram-Schmidt within the group; the subspace is unchanged. - for (pos, &col) in group.iter().enumerate() { - let mut v: Vec = (0..q.nrows()).map(|r| out[[r, col]]).collect(); - for &prev in group.iter().take(pos) { - let mut proj = Complex64::new(0.0, 0.0); - for r in 0..q.nrows() { - proj += out[[r, prev]].conj() * v[r]; - } - for r in 0..q.nrows() { - v[r] -= proj * out[[r, prev]]; + // First attempt: modified Gram-Schmidt within the group. + let mut basis: Vec> = Vec::with_capacity(group.len()); + let mut collapsed = false; + for &col in group { + let mut v: Vec = (0..n).map(|r| q[[r, col]]).collect(); + for b in &basis { + let proj: Complex64 = b.iter().zip(v.iter()).map(|(x, y)| x.conj() * y).sum(); + for r in 0..n { + v[r] -= proj * b[r]; } } let norm: f64 = v.iter().map(|z| z.norm_sqr()).sum::().sqrt(); - if norm > 1e-12 { - for r in 0..q.nrows() { - out[[r, col]] = v[r] / norm; + if norm > 1e-8 { + for x in &mut v { + *x /= norm; } + basis.push(v); + } else { + // Near-linear dependence: Gram-Schmidt cannot repair it. + collapsed = true; + break; + } + } + if !collapsed { + for (pos, &col) in group.iter().enumerate() { + for r in 0..n { + out[[r, col]] = basis[pos][r]; + } + } + continue; + } + + // Fallback: recover an orthonormal basis of the (approximate) + // eigenspace from the SVD null space of `matrix - lambda_bar I`. + let m = group.len(); + let lambda_bar = group.iter().map(|&c| evals[c]).sum::() / m as f64; + let mut shifted = matrix.clone(); + for k in 0..n { + shifted[[k, k]] -= lambda_bar; + } + let fm = to_faer(&shifted); + let svd = fm + .svd() + .map_err(|_| format!("SVD failed on a {n}x{n} degenerate eigenspace"))?; + let v = from_faer(&svd.V()); + // Rank the right singular vectors by the residual |A v_j| (that is, + // by increasing singular value) without relying on an internal + // ordering of the SVD output. + let mut ranked: Vec<(f64, usize)> = (0..n) + .map(|j| { + let mut av = vec![Complex64::new(0.0, 0.0); n]; + for r in 0..n { + let mut acc = Complex64::new(0.0, 0.0); + for k in 0..n { + acc += shifted[[r, k]] * v[[k, j]]; + } + av[r] = acc; + } + let residual = av.iter().map(|z| z.norm_sqr()).sum::().sqrt(); + (residual, j) + }) + .collect(); + ranked.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap_or(std::cmp::Ordering::Equal)); + for (pos, &col) in group.iter().enumerate() { + let src = ranked[pos].1; + for r in 0..n { + out[[r, col]] = v[[r, src]]; } - // A tiny norm keeps the original vector: faer guarantees it is a - // non-zero eigenvector, and near-linear dependence within the - // group cannot be repaired by GS but is no worse than before. } } - out + Ok(out) } /// Builds a complex diagonal matrix from real values (zero imaginary parts). 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 index a3c952fa..f5443cc5 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/mod.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/mod.rs @@ -35,6 +35,13 @@ //! the paper bound `c_n <= 22/48 * 4^n - 3/2 * 2^n + 5/3` //! (n = 3 -> 19, n = 4 -> 95). //! +//! Numerically degenerate inputs may exceed that count by up to two CNOTs: +//! when folding the accumulated A.2 diagonal remainder into a leaf's +//! synthesis target is not numerically feasible (see +//! [`engine::decompose_block_zxz_with_options`]), the remainder is emitted +//! as an explicit diagonal gate instead of aborting the decomposition. +//! Correctness is preserved in both paths. +//! //! Leaf (1q/2q) synthesis reuses the crate's [`super::unitary`] module, the //! same primitives the Python project reaches through `cqlib`. diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs index d77292d9..08552da0 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step1.rs @@ -30,23 +30,43 @@ pub fn is_matrix_unitary(matrix: &Cm, atol: f64) -> bool { } /// Returns whether `matrix` is diagonal within `atol`. +/// +/// A non-finite off-diagonal element counts as "not diagonal". pub fn is_matrix_diagonal(matrix: &Cm, atol: f64) -> bool { let (r, c) = matrix.dim(); for i in 0..r { for j in 0..c { - if i != j && matrix[[i, j]].norm() > atol { - return false; + if i != j { + let m = matrix[[i, j]].norm(); + if !m.is_finite() || m > atol { + return false; + } } } } true } +/// Returns whether every element of `matrix` is finite (neither NaN nor +/// infinite). +pub fn has_finite_elements(matrix: &Cm) -> bool { + matrix.iter().all(|z| z.re.is_finite() && z.im.is_finite()) +} + /// Validates that the input is a `2^n x 2^n` unitary matrix. /// /// Mirrors the Python `assert_square_unitary`; returns `Err(String)` on -/// failure. +/// failure. Rejects `atol` that is not a finite non-negative number, and +/// rejects matrices containing NaN or infinite elements before any +/// numerical decomposition is attempted (a NaN matrix would otherwise +/// slip past the `U^H U ~ I` comparison because NaN comparisons are always +/// false, and then poison the SVD/EVD pipeline). pub fn assert_square_unitary(matrix: &Cm, atol: f64) -> Result<(), String> { + if !atol.is_finite() || atol < 0.0 { + return Err(format!( + "Tolerance atol must be a finite non-negative number, got {atol}." + )); + } if matrix.ndim() != 2 { return Err("Input matrix must be two-dimensional.".into()); } @@ -57,6 +77,9 @@ pub fn assert_square_unitary(matrix: &Cm, atol: f64) -> Result<(), String> { if !is_power_of_two(rows) { return Err("Input matrix dimension must be a power of two.".into()); } + if !has_finite_elements(matrix) { + return Err("Input matrix contains NaN or infinite elements.".into()); + } if !is_unitary(matrix, atol) { return Err("Input matrix must be unitary.".into()); } @@ -66,20 +89,25 @@ pub fn assert_square_unitary(matrix: &Cm, atol: f64) -> Result<(), String> { /// Splits `unitary` into four equal blocks along the most significant qubit. /// /// Mirrors the Python `split_unitary_blocks`; returns `(X, Y, U21, U22)`. -pub fn split_unitary_blocks(unitary: &Cm) -> (Cm, Cm, Cm, Cm) { - assert_square_unitary(unitary, 1e-10).expect("invalid unitary"); +/// The matrix is re-validated with the caller's `atol` (never a hidden +/// fixed tolerance, which would silently disagree with the public one) and +/// validation failures are returned as errors instead of panicking. +pub fn split_unitary_blocks(unitary: &Cm, atol: f64) -> Result<(Cm, Cm, Cm, Cm), String> { + assert_square_unitary(unitary, atol)?; let dim = unitary.nrows(); let half = dim / 2; - ( + Ok(( unitary.slice(s![..half, ..half]).to_owned(), unitary.slice(s![..half, half..]).to_owned(), unitary.slice(s![half.., ..half]).to_owned(), unitary.slice(s![half.., half..]).to_owned(), - ) + )) } /// Polar decomposition through the SVD; returns `(S, U_polar)`. -pub fn polar_from_svd(matrix: &Cm) -> (Cm, Cm) { +/// +/// Numeric failures are returned as errors instead of panicking. +pub fn polar_from_svd(matrix: &Cm) -> Result<(Cm, Cm), String> { super::matrix::polar_from_svd(matrix) } @@ -94,7 +122,7 @@ pub fn compute_c_from_polar(u_x: &Cm, u_y: &Cm) -> Cm { pub fn compute_a1(s_x: &Cm, s_y: &Cm, u_x: &Cm) -> Cm { let mut inner = s_x.clone(); let iy = s_y.mapv(|z| Complex64::new(0.0, 1.0) * z); - inner = inner + &iy; + inner += &iy; mat_mul(&inner, u_x) } @@ -137,9 +165,9 @@ pub fn block_zxz_step1(unitary: &Cm, atol: f64) -> Result<(Cm, Cm, Cm, Cm), Stri return Err("Block-ZXZ Step 1 expects at least a 2-qubit unitary.".into()); } - let (x, y, u21, u22) = split_unitary_blocks(unitary); - let (s_x, u_x) = polar_from_svd(&x); - let (s_y, u_y) = polar_from_svd(&y); + let (x, y, u21, u22) = split_unitary_blocks(unitary, atol)?; + let (s_x, u_x) = polar_from_svd(&x)?; + let (s_y, u_y) = polar_from_svd(&y)?; let c = compute_c_from_polar(&u_x, &u_y); let a1 = compute_a1(&s_x, &s_y, &u_x); diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs index 528bd74c..e8e962d1 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/step2.rs @@ -19,10 +19,11 @@ use super::step1::{assert_square_unitary, is_matrix_diagonal, is_matrix_unitary} /// Schur-style diagonalization of a unitary matrix; returns `(Q, D)`. /// -/// Mirrors the Python `schur_unitary_diagonalize`. +/// Mirrors the Python `schur_unitary_diagonalize`. Numeric failures of the +/// underlying EVD are returned as errors instead of panicking. pub fn schur_unitary_diagonalize(matrix: &Cm, atol: f64) -> Result<(Cm, Cm), String> { assert_square_unitary(matrix, atol)?; - Ok(super::matrix::schur_unitary_diagonalize(matrix)) + super::matrix::schur_unitary_diagonalize(matrix, atol) } /// Builds the diagonal unitary square root `D` from unit-modulus eigenvalues. diff --git a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs index 386a9097..bc8aa039 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/block_zxz/vw.rs @@ -51,6 +51,12 @@ //! `U_next @ D_out`), where it is absorbed by that leaf's own synthesis. The //! temporally last leaf uses the full 0-3 CNOT synthesis to absorb the whole //! accumulated remainder. +//! +//! Absorption can be numerically infeasible: a remainder-folded target often +//! sits on a Weyl-chamber boundary, where the shared two-qubit backend's KAK +//! canonicalization is accurate to only about `1e-10` and its exactness gate +//! rejects every candidate. [`diagonal_gate_circuit`] provides the exact +//! escape hatch used by `engine::run_a2_chain` in that case. use crate::circuit::{Circuit, Parameter, Qubit}; use crate::compile::transform::decompose::unitary::{ @@ -174,6 +180,71 @@ pub fn synth_two_cnot_with_diagonal(target: &Cm) -> Result q0) +/// ``` +/// with `alpha = phi10 - phi00`, `beta = phi01 - phi00` and +/// `gamma = phi11 - phi10 - phi01 + phi00` (the interaction). The +/// controlled phase itself is emitted CX-natively, +/// `CP(gamma) = P(gamma/2; q1) * P(gamma/2; q0) * CX * P(-gamma/2; q0) * CX` +/// so the gate costs exactly two CX and the reported CX count stays +/// truthful; the two `gamma/2` local parts are folded into the `alpha` and +/// `beta` phases of the construction. +/// +/// This is the exact remainder gate of the A.2 fallback: when folding the +/// accumulated diagonal remainder into a leaf's synthesis target is not +/// numerically feasible, the leaf is synthesized directly and the remainder +/// is emitted here instead. The overall phase `e^{i phi00}` is dropped, as +/// only relative phases are observable. +pub fn diagonal_gate_circuit(d: &Cm) -> Result { + if d.dim() != (4, 4) { + return Err("diagonal gate synthesis requires a 4x4 matrix".into()); + } + let mut phases = [0.0f64; 4]; + for i in 0..4 { + for j in 0..4 { + if i != j && d[[i, j]].norm() > 1e-12 { + return Err("diagonal gate synthesis requires a diagonal matrix".into()); + } + } + let value = d[[i, i]]; + if !value.re.is_finite() || !value.im.is_finite() { + return Err("diagonal gate synthesis requires finite entries".into()); + } + if (value.norm() - 1.0).abs() > 1e-9 { + return Err("diagonal gate synthesis requires unit-modulus entries".into()); + } + phases[i] = value.arg(); + } + + let alpha = phases[2] - phases[0]; + let beta = phases[1] - phases[0]; + let gamma = phases[3] - phases[2] - phases[1] + phases[0]; + + let q0 = Qubit::new(0); + let q1 = Qubit::new(1); + let mut circuit = Circuit::new(2); + // CX * Rz(-gamma/2; q0) * CX == diag(1, e^{-i gamma/2}, e^{-i gamma/2}, 1) + // up to a global phase (`Rz` is the engine's emitted gate; its own global + // phase is irrelevant here). + circuit.cx(q1, q0).map_err(|e| e.to_string())?; + circuit.rz(q0, -gamma / 2.0).map_err(|e| e.to_string())?; + circuit.cx(q1, q0).map_err(|e| e.to_string())?; + circuit + .rz(q0, beta + gamma / 2.0) + .map_err(|e| e.to_string())?; + circuit + .rz(q1, alpha + gamma / 2.0) + .map_err(|e| e.to_string())?; + Ok(circuit) +} + /// Counts `CX` gates in a circuit, including nested composite gates. pub fn count_cx(circuit: &Circuit) -> usize { use crate::circuit::gate::Instruction; diff --git a/crates/cqlib-core/src/compile/transform/decompose/mod.rs b/crates/cqlib-core/src/compile/transform/decompose/mod.rs index c356a7dd..9e8ebdd5 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/mod.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/mod.rs @@ -19,10 +19,15 @@ //! 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. It supports one- and two-qubit matrices plus +//! three-or-more-qubit matrices through the [`block_zxz`] engine. //! - [`mc_gate`] provides explicit algorithmic synthesis primitives for //! multi-controlled gates, plus the circuit-level resource-aware //! `decompose_mc_gates` entry point. +//! - [`block_zxz`] decomposes a general n-qubit unitary matrix into +//! single-qubit rotations and CNOTs via the recursive Block-ZXZ method +//! (arXiv:2403.13692), including the paper's A.1/A.2 CNOT-count +//! optimizations. //! //! The workflow-facing adapters [`DecomposeDefinitions`], //! [`DecomposeUnitaries`], and [`DecomposeMcGates`] implement @@ -44,11 +49,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::{ + DecomposeOptions, DecomposeResult, 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..28ddef13 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::block_zxz::DecomposeOptions as BlockZxzDecomposeOptions; use crate::compile::transform::decompose::unitary::TwoQubitSynthesisTarget; use crate::compile::transform::target_basis::TargetBasisSignature; use ndarray::Array2; @@ -161,6 +162,16 @@ pub enum NumericUnitarySynthesisKey { target_basis: Option, fallback_pauli: bool, }, + /// Three-or-more-qubit synthesis through the Block-ZXZ decomposition. + /// + /// The paper Section 5 optimization switches participate in the key so + /// a template synthesized under one configuration is never replayed + /// under another. + BlockZxz { + opt_a1: bool, + opt_a2: bool, + opt_a2_force: bool, + }, } impl NumericUnitarySynthesisKey { @@ -174,6 +185,14 @@ impl NumericUnitarySynthesisKey { fallback_pauli: target.fallback_pauli(), } } + + pub(crate) fn block_zxz(options: &BlockZxzDecomposeOptions) -> Self { + Self::BlockZxz { + opt_a1: options.opt_a1, + opt_a2: options.opt_a2, + opt_a2_force: options.opt_a2_force, + } + } } #[derive(Debug, Clone)] 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..4a0f5354 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/unitary/decompose.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/unitary/decompose.rs @@ -13,11 +13,18 @@ //! 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 -//! `UnitaryGate` operations with standard-gate sequences. Definition expansion +//! 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. //! +//! Three-or-more-qubit unitary gates are synthesized through the recursive +//! Block-ZXZ decomposition (Krol & Al-Ars, arXiv:2403.13692) with the paper's +//! Section 5 CNOT-count optimizations; see +//! [`crate::compile::transform::decompose::block_zxz`]. The optimization +//! switches are configurable through +//! [`UnitaryDecomposeConfig::block_zxz_options`]. +//! //! Preserved operations are copied into a fresh circuit instead of retaining //! source [`CircuitParam`] indices. Their parameters are resolved against the //! source parameter table and interned into the target table. This applies @@ -31,9 +38,8 @@ //! //! 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 -//! rejects unresolved or non-finite unitary parameters, missing matrices, -//! invalid matrix shapes, and unitary gates acting on three or more qubits. +//! contract requires finite numeric unitary matrices. It rejects unresolved or +//! non-finite unitary parameters, missing matrices, and invalid matrix shapes. use super::DeviceTwoQubitSynthesisContext; use super::two_qubit_kak::kak_decompose; @@ -50,6 +56,9 @@ use crate::circuit::{ }; use crate::compile::CompilerError; use crate::compile::transform::analysis::WorkflowCircuitAnalysis; +use crate::compile::transform::decompose::block_zxz::{ + DecomposeOptions as BlockZxzDecomposeOptions, decompose_block_zxz_with_options, +}; use crate::compile::transform::decompose::rule::{ DecompositionRuleCache, DecompositionRuleStats, NumericUnitaryRuleRequest, NumericUnitarySynthesisKey, @@ -59,13 +68,15 @@ use crate::compile::transform::transformer::{PassApplicability, WorkflowPass}; use crate::compile::transform::{CircuitAnalysis, TransformOutcome, Transformer}; use ndarray::Array2; use num_complex::Complex64; -use smallvec::smallvec; +use smallvec::{SmallVec, smallvec}; 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; +/// Absolute tolerance used by Block-ZXZ unitarity and invariant checks. +const BLOCK_ZXZ_ATOL: f64 = 1e-10; /// Configuration for circuit-level matrix-backed `UnitaryGate` synthesis. #[derive(Clone, Debug, PartialEq, Eq)] @@ -75,6 +86,10 @@ pub struct UnitaryDecomposeConfig { /// Whether matrix-backed `UnitaryGate` operations inside control-flow /// bodies should be synthesized recursively. pub recurse_control_flow: bool, + /// Block-ZXZ optimization switches applied to three-or-more-qubit + /// unitary gates (paper Section 5 reductions). Defaults to the fully + /// optimized configuration. + pub block_zxz_options: BlockZxzDecomposeOptions, } impl Default for UnitaryDecomposeConfig { @@ -82,6 +97,7 @@ impl Default for UnitaryDecomposeConfig { Self { two_qubit_target: TwoQubitSynthesisTarget::default(), recurse_control_flow: true, + block_zxz_options: BlockZxzDecomposeOptions::default(), } } } @@ -167,15 +183,20 @@ 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 -/// control-flow bodies, as explicit [`StandardGate::GPhase`] operations. +/// [`UnitaryDecomposeConfig::two_qubit_target`]. Three-or-more-qubit matrices +/// are synthesized through the recursive Block-ZXZ decomposition (standard +/// `U`, `RZ`, `CX`, and `H` gates) with the paper's Section 5 optimizations, +/// configured by [`UnitaryDecomposeConfig::block_zxz_options`]. Synthesized +/// scalar phases are preserved either 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. +/// parameters, no matrix representation, invalid qubit +/// arity, or if the numeric 1q/2q/Block-ZXZ synthesis primitive rejects the +/// matrix. pub fn decompose_unitaries( circuit: &Circuit, config: UnitaryDecomposeConfig, @@ -615,13 +636,50 @@ impl<'a> UnitaryDecomposer<'a> { )?; Ok(decomposition) } - other => Err(CompilerError::TransformFailed { - name: SYNTHESIS_NAME, - reason: format!( - "3q+ UnitaryGate synthesis is not supported yet; gate '{}' has {other} qubits", - gate.label() - ), - }), + // Three or more qubits: synthesize through the recursive + // Block-ZXZ decomposition (paper arXiv:2403.13692), including + // its Section 5 CNOT-count optimizations. + other => { + let options = self.config.block_zxz_options; + let request = NumericUnitaryRuleRequest { + num_qubits: gate.num_qubits(), + matrix: matrix.as_ref(), + synthesis_key: NumericUnitarySynthesisKey::block_zxz(&options), + }; + if let Some((operations, phase_delta)) = self + .rule_cache + .instantiate_numeric_unitary(request.clone(), &operation.qubits)? + { + return Ok(Decomposition { + operations, + phase_delta, + }); + } + let result = decompose_block_zxz_with_options( + matrix.as_ref(), + BLOCK_ZXZ_ATOL, + &options, + ) + .map_err(|source| CompilerError::TransformFailed { + name: SYNTHESIS_NAME, + reason: format!( + "Block-ZXZ synthesis failed for UnitaryGate '{}' with {other} qubits: {source}", + gate.label() + ), + })?; + let decomposition = block_zxz_result_to_decomposition( + &result.circuit, + matrix.as_ref(), + &operation.qubits, + )?; + self.rule_cache.insert_numeric_unitary( + request, + &operation.qubits, + &decomposition.operations, + decomposition.phase_delta, + )?; + Ok(decomposition) + } } } @@ -690,6 +748,105 @@ impl<'a> UnitaryDecomposer<'a> { } } +/// Converts a Block-ZXZ decomposition circuit into pass output. +/// +/// The Block-ZXZ engine acts on local qubit ids `0..n` in the numeric +/// LSB-first circuit basis, while a `UnitaryGate` matrix follows the +/// MSB-first argument order (the first operation qubit is the most +/// significant basis bit). Local qubit `L` therefore maps to +/// `operation_qubits[n - 1 - L]`. +/// +/// The synthesized operations implement `matrix` up to a scalar phase. The +/// compensating phase is measured against the dense matrices and reported +/// through [`Decomposition::phase_delta`], matching the contract of the 1q +/// and 2q synthesis paths (`exp(i * phase_delta) * operations == matrix`). +fn block_zxz_result_to_decomposition( + circuit: &Circuit, + matrix: &Array2, + operation_qubits: &[Qubit], +) -> Result { + let num_qubits = operation_qubits.len(); + let remap = |local: &Qubit| -> Result { + let index = local.index(); + if index >= num_qubits { + return Err(CompilerError::TransformFailed { + name: SYNTHESIS_NAME, + reason: format!( + "Block-ZXZ output references local qubit {index} outside the 0..{num_qubits} argument range" + ), + }); + } + Ok(operation_qubits[num_qubits - 1 - index]) + }; + + let mut operations = Vec::with_capacity(circuit.operations().len()); + for operation in circuit.operations() { + let Instruction::Standard(gate) = &operation.instruction else { + return Err(CompilerError::TransformFailed { + name: SYNTHESIS_NAME, + reason: format!( + "Block-ZXZ output contains non-standard instruction '{}'; only U/RZ/CX/H gates are expected", + operation.instruction.name() + ), + }); + }; + let qubits: SmallVec<[Qubit; 3]> = operation + .qubits + .iter() + .map(&remap) + .collect::>()?; + let mut params: SmallVec<[ParameterValue; 1]> = SmallVec::new(); + for param in &operation.params { + match param { + CircuitParam::Fixed(value) => params.push(ParameterValue::Fixed(*value)), + CircuitParam::Index(_) => { + return Err(CompilerError::TransformFailed { + name: SYNTHESIS_NAME, + reason: "Block-ZXZ output contains an unresolved symbolic parameter" + .to_string(), + }); + } + } + } + operations.push(ValueOperation { + instruction: ValueInstruction::from_instruction(Instruction::Standard(*gate)), + qubits, + params, + label: None, + }); + } + + // Measure the compensating global phase. The dense matrix of the + // synthesized circuit (global phase included) equals e^{i delta} times + // the target matrix; the operations alone therefore equal + // e^{i (delta - global_phase)} times the target, and the pass must add + // back `global_phase - delta`. + let dense = circuit + .to_matrix(None) + .map_err(|source| CompilerError::TransformFailed { + name: SYNTHESIS_NAME, + reason: format!("failed to rebuild Block-ZXZ output matrix: {source}"), + })?; + let global_phase = + circuit + .global_phase() + .evaluate(&None) + .map_err(|_| CompilerError::TransformFailed { + name: SYNTHESIS_NAME, + reason: "Block-ZXZ output carries a non-numeric global phase".to_string(), + })?; + let mut overlap = Complex64::new(0.0, 0.0); + for ((row, col), &value) in matrix.indexed_iter() { + overlap += value.conj() * dense[[row, col]]; + } + let phase_delta = global_phase - overlap.arg(); + + Ok(Decomposition { + operations, + phase_delta, + }) +} + #[cfg(test)] mod tests { use super::*; @@ -731,6 +888,112 @@ mod tests { } } + /// Deterministic xorshift64* pseudo-random generator (mirrors the + /// Block-ZXZ integration and C-binding test helpers). + struct Rng(u64); + + impl Rng { + fn new(seed: u64) -> Self { + Rng(seed.wrapping_add(0x9E37_79B9_7F4A_7C15)) + } + fn next(&mut self) -> u64 { + let mut x = self.0; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + self.0 = x; + x.wrapping_mul(0x2545_F491_4F6C_DD1D) + } + fn f64(&mut self) -> f64 { + (self.next() >> 11) as f64 / ((1u64 << 53) as f64) + } + fn gaussian(&mut self) -> f64 { + let u1 = self.f64().max(1e-300); + let u2 = self.f64(); + (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos() + } + } + + /// Generates a deterministic random `num_qubits`-qubit unitary through + /// complex Gram-Schmidt orthonormalization (no external crate needed). + /// With `seed = 7` the generic (non-block-diagonal, KAK-generic) inputs + /// hit the paper's exact CNOT counts: n=3 -> 19 optimized / 24 + /// unoptimized, n=4 -> 95. + fn random_unitary(num_qubits: usize, seed: u64) -> Array2 { + let dim = 1usize << num_qubits; + let mut rng = Rng::new(seed); + let source: Vec> = (0..dim) + .map(|_| { + (0..dim) + .map(|_| Complex64::new(rng.gaussian(), rng.gaussian())) + .collect() + }) + .collect(); + // Complex Gram-Schmidt on the columns of `source` -> unitary Q. + let one = Complex64::new(1.0, 0.0); + let mut q: Vec> = vec![vec![Complex64::new(0.0, 0.0); dim]; dim]; + for col in 0..dim { + for row in 0..dim { + q[col][row] = source[row][col]; + } + for prev in 0..col { + let mut proj = Complex64::new(0.0, 0.0); + for (reference, current) in q[prev].iter().zip(&q[col]) { + proj += reference.conj() * current; + } + let basis = q[prev].clone(); + for row in 0..dim { + q[col][row] -= proj * basis[row]; + } + } + let mut norm = 0.0f64; + for value in &q[col] { + norm += value.norm_sqr(); + } + let norm = norm.sqrt(); + if norm > 0.0 { + for value in &mut q[col] { + *value /= norm; + } + } else { + q[col][col] = one; + } + } + let mut out = Array2::::zeros((dim, dim)); + for col in 0..dim { + for row in 0..dim { + out[[row, col]] = q[col][row]; + } + } + out + } + + /// Counts the standard-gate operations matching `gate`. + fn count_standard_gates(circuit: &Circuit, gate: StandardGate) -> usize { + circuit + .operations() + .iter() + .filter(|op| matches!(op.instruction, Instruction::Standard(g) if g == gate)) + .count() + } + + /// Asserts that a top-level Block-ZXZ synthesis result only contains + /// the gates the engine emits (`U`, `RZ`, `CX`, `H`). + fn assert_only_block_zxz_output_gates(circuit: &Circuit) { + for operation in circuit.operations() { + assert!( + matches!( + operation.instruction, + Instruction::Standard( + StandardGate::U | StandardGate::RZ | StandardGate::CX | StandardGate::H + ) + ), + "unexpected non-Block-ZXZ instruction: {:?}", + operation.instruction + ); + } + } + #[test] fn weyl_boundary_unitary_gate_decomposition_preserves_phase_and_device_constraints() { use crate::compile::test_utils::{build_device_synthesis_context, kak_boundary_matrix}; @@ -1636,16 +1899,206 @@ mod tests { } #[test] - fn rejects_three_qubit_unitary_gate() { + fn decomposes_three_qubit_unitary_gate() { let gate = UnitaryGate::new("custom_3q", 3, 0) - .with_matrix(Array2::eye(8)) + .with_matrix(random_unitary(3, 7)) .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")); + let expected = circuit_to_matrix(&circuit, None).unwrap(); + let decomposed = decompose_unitaries(&circuit, UnitaryDecomposeConfig::default()).unwrap(); + + assert_only_block_zxz_output_gates(&decomposed); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&decomposed, None).unwrap(), + epsilon = 1e-9 + ); + // Paper Table 1: a generic three-qubit unitary costs 19 CNOTs with + // both Section 5 optimizations enabled. + assert_eq!(count_standard_gates(&decomposed, StandardGate::CX), 19); + } + + #[test] + fn decomposes_four_qubit_unitary_gate() { + let gate = UnitaryGate::new("custom_4q", 4, 0) + .with_matrix(random_unitary(4, 7)) + .unwrap(); + let mut circuit = Circuit::new(4); + circuit + .unitary( + gate, + vec![Qubit::new(0), Qubit::new(1), Qubit::new(2), Qubit::new(3)], + ) + .unwrap(); + + let expected = circuit_to_matrix(&circuit, None).unwrap(); + let decomposed = decompose_unitaries(&circuit, UnitaryDecomposeConfig::default()).unwrap(); + + assert_only_block_zxz_output_gates(&decomposed); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&decomposed, None).unwrap(), + epsilon = 1e-9 + ); + // Paper Table 1: a generic four-qubit unitary costs 95 CNOTs. + assert_eq!(count_standard_gates(&decomposed, StandardGate::CX), 95); + } + + #[test] + fn three_qubit_gate_maps_reversed_argument_order() { + let gate = UnitaryGate::new("custom_3q", 3, 0) + .with_matrix(random_unitary(3, 7)) + .unwrap(); + // The first gate argument is the most significant basis bit, so + // qubit 2 carries the top matrix row/column index. A wrong local + // remap direction cannot reproduce this circuit's matrix. + let mut circuit = Circuit::new(3); + circuit + .unitary(gate, vec![Qubit::new(2), Qubit::new(0), Qubit::new(1)]) + .unwrap(); + + let expected = circuit_to_matrix(&circuit, None).unwrap(); + let decomposed = decompose_unitaries(&circuit, UnitaryDecomposeConfig::default()).unwrap(); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&decomposed, None).unwrap(), + epsilon = 1e-9 + ); + } + + #[test] + fn reuses_block_zxz_rule_for_identical_matrix() { + let gate = UnitaryGate::new("custom_3q", 3, 0) + .with_matrix(random_unitary(3, 7)) + .unwrap(); + let mut circuit = Circuit::new(3); + circuit + .unitary( + gate.clone(), + vec![Qubit::new(0), Qubit::new(1), Qubit::new(2)], + ) + .unwrap(); + circuit + .unitary(gate, vec![Qubit::new(2), Qubit::new(1), Qubit::new(0)]) + .unwrap(); + + let expected = circuit_to_matrix(&circuit, None).unwrap(); + let (resolved, stats) = + decompose_unitaries_with_rule_stats(&circuit, UnitaryDecomposeConfig::default()) + .unwrap(); + assert_eq!(stats.hits, 1); + assert_eq!(stats.misses, 1); + assert!(resolved.changed); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&resolved.circuit, None).unwrap(), + epsilon = 1e-9 + ); + } + + #[test] + fn block_zxz_options_toggle_cx_count() { + let gate = UnitaryGate::new("custom_3q", 3, 0) + .with_matrix(random_unitary(3, 7)) + .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(&circuit, None).unwrap(); + + let optimized = decompose_unitaries(&circuit, UnitaryDecomposeConfig::default()).unwrap(); + let unoptimized = decompose_unitaries( + &circuit, + UnitaryDecomposeConfig { + block_zxz_options: BlockZxzDecomposeOptions::none(), + ..Default::default() + }, + ) + .unwrap(); + + // Paper Table 1: a generic three-qubit unitary costs 24 CNOTs + // unoptimized and 19 with both Section 5 reductions enabled + // (A.1 saves 2 CNOTs on the single recursion layer, A.2 saves 3 + // on the two-qubit leaves). + let optimized_cx = count_standard_gates(&optimized, StandardGate::CX); + let unoptimized_cx = count_standard_gates(&unoptimized, StandardGate::CX); + assert_eq!(optimized_cx, 19); + assert_eq!(unoptimized_cx, 24); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&optimized, None).unwrap(), + epsilon = 1e-9 + ); + assert_abs_diff_eq!( + expected, + circuit_to_matrix(&unoptimized, None).unwrap(), + epsilon = 1e-9 + ); + } + + #[test] + fn decomposes_three_qubit_unitary_gate_inside_control_flow() { + let phase = Complex64::from_polar(1.0, 0.25); + let gate = UnitaryGate::new("phase_3q", 3, 0) + .with_matrix(random_unitary(3, 7).mapv(|value| phase * value)) + .unwrap(); + let mut circuit = Circuit::new(4); + circuit + .if_else( + ClassicalExpr::bool_literal(true), + |body| { + body.append( + Instruction::UnitaryGate(Box::new(gate)), + [Qubit::new(1), Qubit::new(3), Qubit::new(0)], + Vec::::new(), + None, + ) + }, + |_| Ok(()), + ) + .unwrap(); + + let decomposed = decompose_unitaries(&circuit, UnitaryDecomposeConfig::default()).unwrap(); + assert!(decomposed.global_phase().is_zero()); + let Instruction::ClassicalControl(ClassicalControlOp::If(op)) = + &decomposed.operations()[0].instruction + else { + panic!("expected if operation"); + }; + let body = op.then_body(); + assert!(matches!( + body.operations()[0].instruction, + Instruction::Standard(StandardGate::GPhase) + )); + for operation in body.operations() { + assert!( + !matches!(operation.instruction, Instruction::UnitaryGate(_)), + "3q unitary gate was not synthesized inside the control-flow body" + ); + for qubit in &operation.qubits { + assert!( + [1usize, 3, 0].contains(&qubit.index()), + "synthesized operation leaked outside the gate qubits" + ); + } + } + } + + #[test] + fn rejects_non_unitary_three_qubit_matrix() { + // Gate construction rejects non-unitary matrices (UNITARITY_EPS + // matches the pass synthesis tolerance), so a scaled identity can + // never reach the Block-ZXZ synthesis path. + let matrix = Array2::::eye(8).mapv(|value| value * Complex64::new(2.0, 0.0)); + let err = UnitaryGate::new("scaled_3q", 3, 0) + .with_matrix(matrix) + .unwrap_err(); + assert!(matches!(err, CircuitError::InvalidOperation(_))); + assert!(err.to_string().contains("Matrix is not unitary")); } } 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..a747daec 100644 --- a/crates/cqlib-core/src/compile/transform/decompose/unitary/mod.rs +++ b/crates/cqlib-core/src/compile/transform/decompose/unitary/mod.rs @@ -20,9 +20,11 @@ //! # Supported inputs //! //! The circuit-facing pass supports fixed numeric one- and two-qubit 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, and synthesizes three-or-more-qubit matrices through the +//! recursive Block-ZXZ engine +//! ([`block_zxz`](super::block_zxz), arXiv:2403.13692). A parameterized +//! matrix is supported only after every argument at the call site resolves +//! to a finite numeric value. //! //! This module does not expand circuit-backed definitions or adapt gates to //! hardware topology. It also does not perform target-basis lowering itself; From 91a7cebd8608ab64dc15434e452c5b23c8b3c531 Mon Sep 17 00:00:00 2001 From: Chen <17748292+chen-xinmiao1@user.noreply.gitee.com> Date: Tue, 3 Nov 2026 11:04:15 +0800 Subject: [PATCH 4/4] feat: controlled composite quantum gate --- crates/binding-c/src/circuit/advanced.rs | 54 +++++++++++++++++++ .../cqlib/circuit/gates/circuit_gate.pyi | 31 +++++++++++ .../cqlib/circuit/gates/mc_gate.pyi | 14 +++++ .../cqlib/circuit/gates/standard.pyi | 4 +- .../cqlib/circuit/gates/unitary.pyi | 21 ++++++++ .../src/circuit/gate/circuit_gate.rs | 41 ++++++++++++++ .../src/circuit/gate/mc_gate.rs | 49 +++++++++++++++++ .../src/circuit/gate/standard.rs | 4 ++ .../src/circuit/gate/unitary.rs | 45 ++++++++++++++++ .../src/circuit/gate/circuit_gate.rs | 44 ++++++++++++++- .../src/circuit/gate/instruction.rs | 32 ++++++++++- .../src/qis/state/density_matrix.rs | 6 +++ .../src/qis/state/density_matrix_noise.rs | 7 +++ .../cqlib-core/src/qis/state/statevector.rs | 6 +++ 14 files changed, 353 insertions(+), 5 deletions(-) diff --git a/crates/binding-c/src/circuit/advanced.rs b/crates/binding-c/src/circuit/advanced.rs index 24dba0a3..af1c6ee2 100644 --- a/crates/binding-c/src/circuit/advanced.rs +++ b/crates/binding-c/src/circuit/advanced.rs @@ -813,6 +813,60 @@ pub extern "C" fn circuit_circuit_gate( .map_or(-3, |_| 0) } +/// Append a controlled composite gate. +/// +/// Adds `controls_len` control qubits to the circuit-defined `gate` and +/// appends the result. The operation's qubit list is `controls` followed by +/// `targets` (controls are the most-significant bits, matching +/// `circuit_multi_control`); `targets` map positionally onto the gate's own +/// arguments and `params` bind positionally to its parameter signature. The +/// controlled gate stays symbolic: concrete matrices are materialized only +/// when the circuit is executed. Returns 0 on success, -1 on NULL input, +/// -2 on out-of-bounds qubits, -3 when the definition is not unitary or the +/// arity mismatches, -8 on a zero control count. +#[allow(clippy::too_many_arguments)] +#[unsafe(no_mangle)] +pub extern "C" fn circuit_gate_control( + ptr: *mut CCircuit, + gate: *const CCircuitGate, + controls: *const u32, + controls_len: usize, + targets: *const u32, + targets_len: usize, + params: *const *const CParameter, + params_len: usize, +) -> i32 { + if ptr.is_null() || gate.is_null() { + return -1; + } + if controls_len == 0 { + return -8; + } + let wrapper = unsafe { &mut *ptr }; + let controls = match checked_qubits(&wrapper.inner, controls, controls_len) { + Ok(controls) => controls, + Err(code) => return code, + }; + let targets = match checked_qubits(&wrapper.inner, targets, targets_len) { + Ok(targets) => targets, + Err(code) => return code, + }; + let params = match param_ptrs_to_values(params, params_len) { + Ok(params) => params, + Err(code) => return code, + }; + let instruction = Instruction::CircuitGate(Box::new(unsafe { (*gate).inner.clone() })); + let Some(controlled) = instruction.control(controls_len) else { + return -3; + }; + let mut qubits = controls; + qubits.extend(targets); + wrapper + .inner + .append(controlled, qubits, params, None) + .map_or(-3, |_| 0) +} + /// Append a multi-controlled standard gate. /// /// `gate_name` is a standard-gate name ("X", "RX", "SWAP", ...; the same diff --git a/crates/binding-python/cqlib/circuit/gates/circuit_gate.pyi b/crates/binding-python/cqlib/circuit/gates/circuit_gate.pyi index 742aa1b7..3eacbd76 100644 --- a/crates/binding-python/cqlib/circuit/gates/circuit_gate.pyi +++ b/crates/binding-python/cqlib/circuit/gates/circuit_gate.pyi @@ -64,6 +64,7 @@ Classes from ..bit import Qubit from ..classical import ClassicalType from ..operation import ValueOperation +from .unitary import UnitaryGate class FrozenCircuit: """Immutable circuit snapshot suitable for use inside a gate definition. @@ -229,6 +230,36 @@ class CircuitGate: """ ... + def control(self, num_controls: int = ...) -> UnitaryGate: + """Return a controlled version of this composite gate. + + The composite definition is embedded into a block-diagonal controlled + matrix (new control qubits first, most-significant) and wrapped as a + :class:`~cqlib.circuit.gates.UnitaryGate` whose positional parameter + signature matches this gate's. The wrapped definition stays + symbolic: concrete matrices are materialized only when the circuit is + executed, so :meth:`Circuit.to_gate` followed by ``control()`` keeps + the hierarchical definition until simulation time. + + Args: + num_controls: Number of control qubits to add (default 1). + + Returns: + A ``UnitaryGate`` acting on ``num_controls + num_qubits`` qubits. + The first ``num_controls`` application qubits are the controls. + + Raises: + ValueError: If ``num_controls`` is zero. + CircuitError: If the backing circuit is not a unitary definition + (e.g. it contains measurement or reset). + + Example:: + + bell = bell_circuit.to_gate("Bell").control(1) + outer.append_unitary_gate(bell, [control, target0, target1]) + """ + ... + def __eq__(self, other: object) -> bool: """Equality compares logical identity (name and circuit definition). diff --git a/crates/binding-python/cqlib/circuit/gates/mc_gate.pyi b/crates/binding-python/cqlib/circuit/gates/mc_gate.pyi index 5f96f9b5..abaf5420 100644 --- a/crates/binding-python/cqlib/circuit/gates/mc_gate.pyi +++ b/crates/binding-python/cqlib/circuit/gates/mc_gate.pyi @@ -53,6 +53,20 @@ class MCGate: The inverse of C(U) is C(U†). """ ... + def control(self, num_controls: int = ...) -> MCGate: + """Return a version with additional control qubits. + + The new controls are aggregated with the existing ones, preserving + the base gate and any bound parameters. + + Args: + num_controls: Number of additional control qubits (default 1). + + Raises: + ValueError: If ``num_controls`` is zero or the total control + count overflows the supported range. + """ + ... @property def num_ctrl_qubits(self) -> int: """Number of control qubits.""" diff --git a/crates/binding-python/cqlib/circuit/gates/standard.pyi b/crates/binding-python/cqlib/circuit/gates/standard.pyi index 2e0acb66..5d4cb384 100644 --- a/crates/binding-python/cqlib/circuit/gates/standard.pyi +++ b/crates/binding-python/cqlib/circuit/gates/standard.pyi @@ -145,11 +145,11 @@ class StandardGate: """ ... - def control(self, num_controls: int) -> MCGate: + def control(self, num_controls: int = ...) -> MCGate: """Return a multi-controlled form of this gate. Args: - num_controls: Number of additional control qubits. + num_controls: Number of additional control qubits (default 1). """ ... diff --git a/crates/binding-python/cqlib/circuit/gates/unitary.pyi b/crates/binding-python/cqlib/circuit/gates/unitary.pyi index d2cad85d..f29531b6 100644 --- a/crates/binding-python/cqlib/circuit/gates/unitary.pyi +++ b/crates/binding-python/cqlib/circuit/gates/unitary.pyi @@ -99,6 +99,27 @@ class UnitaryGate: params: Numeric values for each positional parameter. """ ... + def control(self, num_controls: int = ...) -> UnitaryGate: + """Return a controlled version of this unitary gate. + + The gate's matrix (numeric or symbolic) is embedded into a + block-diagonal controlled matrix with the new control qubits as the + most-significant bits. Symbolic definitions stay symbolic; concrete + matrices are materialized only at circuit execution time. + + Args: + num_controls: Number of control qubits to add (default 1). + + Returns: + A new ``UnitaryGate`` acting on ``num_controls + num_qubits`` + qubits; the first ``num_controls`` application qubits are the + controls. The label becomes ``ctl_{num_controls}_{label}``. + + Raises: + ValueError: If ``num_controls`` is zero. + CircuitError: If the gate has no matrix representation to control. + """ + ... def __array__( self, dtype: Any | None = ..., copy: bool | None = ... ) -> NDArray[np.complex128]: diff --git a/crates/binding-python/src/circuit/gate/circuit_gate.rs b/crates/binding-python/src/circuit/gate/circuit_gate.rs index 87cafe6e..7a9b78d6 100644 --- a/crates/binding-python/src/circuit/gate/circuit_gate.rs +++ b/crates/binding-python/src/circuit/gate/circuit_gate.rs @@ -19,9 +19,12 @@ use crate::circuit::bit::PyQubit; use crate::circuit::classical::PyClassicalType; use crate::circuit::error::CircuitError as PyCircuitError; +use crate::circuit::gate::PyUnitaryGate; use crate::circuit::operation::PyValueOperation; use cqlib_core::circuit::Circuit; +use cqlib_core::circuit::Instruction; use cqlib_core::circuit::gate::{CircuitGate, FrozenCircuit}; +use pyo3::exceptions::PyValueError; use pyo3::prelude::*; /// Immutable circuit definition suitable for use inside a gate. @@ -219,6 +222,44 @@ impl PyCircuitGate { .map_err(|error| PyCircuitError::new_err(error.to_string())) } + /// Returns a controlled version of this composite gate. + /// + /// The composite definition is embedded into a block-diagonal controlled + /// matrix (new control qubits first, most-significant) and wrapped as a + /// :class:`~cqlib.circuit.gates.UnitaryGate` whose positional parameter + /// signature matches this gate's. The wrapped definition stays symbolic: + /// concrete matrices are materialized only when the circuit is executed. + /// + /// Args: + /// num_controls: Number of control qubits to add (default 1). + /// + /// Returns: + /// A `UnitaryGate` acting on ``num_controls + num_qubits`` qubits. The + /// first ``num_controls`` application qubits are the controls. + /// + /// Raises: + /// ValueError: If ``num_controls`` is zero. + /// CircuitError: If the backing circuit is not a unitary definition + /// (e.g. it contains measurement or reset). + /// + /// Example: + /// bell = bell_circuit.to_gate("Bell").control(1) + /// outer.append_unitary_gate(bell, [control, target0, target1]) + #[pyo3(signature = (num_controls=1))] + fn control(&self, num_controls: usize) -> PyResult { + if num_controls == 0 { + return Err(PyValueError::new_err( + "num_controls must be at least 1; append the gate directly for zero controls", + )); + } + match Instruction::CircuitGate(Box::new(self.inner.clone())).control(num_controls) { + Some(Instruction::UnitaryGate(gate)) => Ok(PyUnitaryGate::from(*gate)), + _ => Err(PyCircuitError::new_err( + "controlled composite gate requires a unitary circuit definition".to_string(), + )), + } + } + /// Structural equality: name, ordered signature, and defining circuit. fn __eq__(&self, other: &PyCircuitGate) -> bool { self.inner == other.inner diff --git a/crates/binding-python/src/circuit/gate/mc_gate.rs b/crates/binding-python/src/circuit/gate/mc_gate.rs index 5e4ec41f..fefc2568 100644 --- a/crates/binding-python/src/circuit/gate/mc_gate.rs +++ b/crates/binding-python/src/circuit/gate/mc_gate.rs @@ -19,11 +19,13 @@ use crate::circuit::PyStandardGate; use crate::circuit::error::{CircuitError as PyCircuitError, ParameterError as PyParameterError}; use crate::circuit::parameter::PyParameter; use crate::utils::hash_value; +use cqlib_core::circuit::Instruction; use cqlib_core::circuit::Parameter; use cqlib_core::circuit::error::ParameterError; use cqlib_core::circuit::gate::MCGate; use num_complex::Complex64; use numpy::{PyArray2, ToPyArray}; +use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::{PyResult, pyclass, pymethods}; use std::fmt; @@ -145,6 +147,53 @@ impl PyMcGate { } } + /// Returns a controlled version of this multi-controlled gate. + /// + /// The new controls are aggregated with the existing ones, preserving the + /// bound parameters. Inherent controls of a pre-controlled base gate + /// (e.g. ``MCGate(1, CX)``) are counted once, mirroring the core's + /// canonicalization. + /// + /// Args: + /// num_controls: Number of additional control qubits (default 1). + /// + /// Returns: + /// A new ``MCGate`` over the canonical base gate with the aggregated + /// total control count. Promotable totals keep the same semantics as + /// the equivalent standard gate. + /// + /// Raises: + /// ValueError: If ``num_controls`` is zero. + /// CircuitError: If the gate cannot be controlled. + #[pyo3(signature = (num_controls=1))] + pub fn control(&self, num_controls: usize) -> PyResult { + if num_controls == 0 { + return Err(PyValueError::new_err( + "num_controls must be at least 1; use the gate directly for zero controls", + )); + } + let controlled = Instruction::McGate(Box::new(self.inner.clone())) + .control(num_controls) + .ok_or_else(|| { + PyCircuitError::new_err("multi-controlled gate cannot be controlled".to_string()) + })?; + match controlled { + Instruction::McGate(gate) => Ok(Self { + inner: *gate, + params: self.params.clone(), + }), + // Promotable totals collapse into a dedicated StandardGate (e.g. + // MCGate(1, X).control(1) -> CCX). Keep the MCGate wrapper by + // re-attaching the standard form with zero extra controls: its + // control count, qubit count, and matrix are identical. + Instruction::Standard(std) => Ok(Self { + inner: MCGate::new(0, std), + params: self.params.clone(), + }), + _ => unreachable!("control on an MCGate yields an MCGate or Standard"), + } + } + /// Returns the number of control qubits. #[getter] pub fn num_ctrl_qubits(&self) -> usize { diff --git a/crates/binding-python/src/circuit/gate/standard.rs b/crates/binding-python/src/circuit/gate/standard.rs index 160b2508..1e3788f8 100644 --- a/crates/binding-python/src/circuit/gate/standard.rs +++ b/crates/binding-python/src/circuit/gate/standard.rs @@ -325,6 +325,10 @@ impl PyStandardGate { } /// Returns a multi-controlled form of this standard gate. + /// + /// Args: + /// num_controls: Number of control qubits to add (default 1). + #[pyo3(signature = (num_controls=1))] fn control(&self, num_controls: u8) -> PyMcGate { PyMcGate { inner: MCGate::new(num_controls, self.inner), diff --git a/crates/binding-python/src/circuit/gate/unitary.rs b/crates/binding-python/src/circuit/gate/unitary.rs index 4a87bb6a..d11ad515 100644 --- a/crates/binding-python/src/circuit/gate/unitary.rs +++ b/crates/binding-python/src/circuit/gate/unitary.rs @@ -20,9 +20,11 @@ use crate::circuit::gate::PyFrozenCircuit; use crate::circuit::symbolic_matrix::PySymbolicMatrix; use crate::utils::hash_value; use cqlib_core::circuit::CircuitError; +use cqlib_core::circuit::Instruction; use cqlib_core::circuit::gate::UnitaryGate; use num_complex::Complex64; use numpy::{PyArray2, PyArrayMethods}; +use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use pyo3::{PyResult, Python, pyclass, pymethods}; use std::sync::Arc; @@ -179,6 +181,49 @@ impl PyUnitaryGate { .map_err(|error| PyCircuitError::new_err(error.to_string())) } + /// Returns a controlled version of this unitary gate. + /// + /// The gate's matrix (numeric or symbolic) is embedded into a + /// block-diagonal controlled matrix with the new control qubits as the + /// most-significant bits. Symbolic definitions stay symbolic; concrete + /// matrices are materialized only at circuit execution time. + /// + /// Args: + /// num_controls: Number of control qubits to add (default 1). + /// + /// Returns: + /// A new ``UnitaryGate`` acting on ``num_controls + num_qubits`` + /// qubits; the first ``num_controls`` application qubits are the + /// controls. The label becomes ``ctl_{num_controls}_{label}``. + /// + /// Raises: + /// ValueError: If ``num_controls`` is zero. + /// CircuitError: If the gate has no matrix representation to control. + #[pyo3(signature = (num_controls=1))] + fn control(&self, num_controls: usize) -> PyResult { + if num_controls == 0 { + return Err(PyValueError::new_err( + "num_controls must be at least 1; use the gate directly for zero controls", + )); + } + if self.inner.matrix().is_none() + && self.inner.symbolic_matrix().is_none() + && self.inner.circuit().is_none() + { + // Controlling a definition-less gate would yield a matrix-less + // result that can never execute; reject it up front. + return Err(PyCircuitError::new_err( + CircuitError::NoMatrixRepresentation.to_string(), + )); + } + match Instruction::UnitaryGate(Box::new(self.inner.clone())).control(num_controls) { + Some(Instruction::UnitaryGate(gate)) => Ok(Self { inner: *gate }), + _ => Err(PyCircuitError::new_err( + CircuitError::NoMatrixRepresentation.to_string(), + )), + } + } + /// Implements the numpy array protocol for numpy 2.0+ compatibility. /// /// Allows direct conversion to numpy array: `np.array(gate)` or `gate.matrix`. diff --git a/crates/cqlib-core/src/circuit/gate/circuit_gate.rs b/crates/cqlib-core/src/circuit/gate/circuit_gate.rs index 5eaf87a9..71c4505f 100644 --- a/crates/cqlib-core/src/circuit/gate/circuit_gate.rs +++ b/crates/cqlib-core/src/circuit/gate/circuit_gate.rs @@ -30,7 +30,7 @@ use std::sync::{Arc, OnceLock}; /// An immutable, frozen circuit for use in gate definitions. /// /// `FrozenCircuit` wraps a [`Circuit`] in an immutable container, ensuring -/// that the circuit definition cannot be modified after creation. This is +/// that the circuit definition cannot be modified after creation. This is /// essential for maintaining consistency when circuits are used as gate /// definitions. /// @@ -52,6 +52,7 @@ pub struct FrozenCircuit { used_symbols: Arc>, symbolic_matrix_cache: Arc>>, storage_order_symbolic_matrix_cache: Arc>>, + gate_order_symbolic_matrix_cache: Arc>>, } impl FrozenCircuit { @@ -74,6 +75,7 @@ impl FrozenCircuit { used_symbols, symbolic_matrix_cache: Arc::new(OnceLock::new()), storage_order_symbolic_matrix_cache: Arc::new(OnceLock::new()), + gate_order_symbolic_matrix_cache: Arc::new(OnceLock::new()), } } @@ -148,6 +150,33 @@ impl FrozenCircuit { .cloned() .unwrap_or(matrix)) } + + /// The gate-argument basis used by matrix-backed composite-gate + /// construction: the first application argument is the most-significant + /// bit, matching standard gate matrices. + fn symbolic_matrix_in_gate_order(&self) -> Result, CircuitError> { + if let Some(matrix) = self.gate_order_symbolic_matrix_cache.get() { + return Ok(matrix.clone()); + } + + // `circuit_to_symbolic_matrix` takes an LSB-first order, so reversing + // the storage order puts the first storage qubit (the first + // application argument) at the most-significant bit. + let order: Vec = self + .circuit + .qubits() + .iter() + .rev() + .map(|q| q.index()) + .collect(); + let matrix = Arc::new(circuit_to_symbolic_matrix(&self.circuit, Some(&order))?); + let _ = self.gate_order_symbolic_matrix_cache.set(matrix.clone()); + Ok(self + .gate_order_symbolic_matrix_cache + .get() + .cloned() + .unwrap_or(matrix)) + } } impl PartialEq for FrozenCircuit { @@ -431,6 +460,19 @@ impl CircuitGate { self.circuit.symbolic_matrix_in_storage_order() } + /// Returns the cached symbolic matrix in gate-argument order. + /// + /// The first application argument is the most-significant bit, matching + /// the convention of standard gate matrices and explicit + /// [`UnitaryGate`](crate::circuit::gate::UnitaryGate) matrices. Composite + /// controlled-gate construction uses this basis so that prepended + /// control qubits line up with the controlled block embedding. + pub(crate) fn symbolic_matrix_in_gate_order( + &self, + ) -> Result, CircuitError> { + self.circuit.symbolic_matrix_in_gate_order() + } + /// Returns the name of this circuit gate. /// /// # Examples diff --git a/crates/cqlib-core/src/circuit/gate/instruction.rs b/crates/cqlib-core/src/circuit/gate/instruction.rs index 7047f713..e085c44c 100644 --- a/crates/cqlib-core/src/circuit/gate/instruction.rs +++ b/crates/cqlib-core/src/circuit/gate/instruction.rs @@ -421,6 +421,10 @@ impl Instruction { /// 2. **Fallback**: If no standard equivalent exists (e.g., $C^3-X$), it returns /// an [`Instruction::McGate`]. /// 3. **Aggregation**: If the instruction is already an `MCGate`, the new controls are merged into it. + /// 4. **Composite gates**: A `CircuitGate` is embedded into a block-diagonal controlled + /// matrix (controls as most-significant bits) and returned as a symbolic + /// [`Instruction::UnitaryGate`]. The wrapped definition stays symbolic; concrete + /// matrices are only materialized at circuit execution time. /// /// # Arguments /// @@ -430,7 +434,7 @@ impl Instruction { /// /// - `Some(Instruction)`: The new controlled instruction. /// - `None`: If the instruction cannot be controlled (e.g., `Barrier`, `Measure`, - /// or classical control). + /// classical control, or a non-unitary circuit definition). pub fn control(&self, num_new_ctrls: usize) -> Option { if num_new_ctrls == 0 { return Some(self.clone()); @@ -495,7 +499,31 @@ impl Instruction { Some(Instruction::UnitaryGate(Box::from(g))) } - Instruction::CircuitGate(_) => None, // CircuitGate does not support control yet + Instruction::CircuitGate(circuit_gate) => { + // Guard against bit-shift overflow in the controlled block + // embedding; realistic control counts stay far below this. + if num_new_ctrls >= usize::BITS as usize { + return None; + } + + // Gate-order basis (first application argument = MSB), so the + // controlled embedding places the new control qubits at the + // most-significant bits, ahead of the composite gate's own + // arguments. + let base = circuit_gate.symbolic_matrix_in_gate_order().ok()?; + let controlled = + crate::circuit::symbolic_matrix::gate::control_matrix(&base, num_new_ctrls); + let total_qubits = circuit_gate.num_qubits() + num_new_ctrls; + let label = format!("ctl_{}_{}", num_new_ctrls, circuit_gate.name()); + let unitary = UnitaryGate::new( + label.as_str(), + total_qubits as u16, + circuit_gate.num_params() as u16, + ) + .with_symbolic_matrix(circuit_gate.signature_params().iter().cloned(), controlled) + .ok()?; + Some(Instruction::UnitaryGate(Box::from(unitary))) + } Instruction::Directive(_) => None, Instruction::ClassicalData(_) => None, Instruction::Delay => None, diff --git a/crates/cqlib-core/src/qis/state/density_matrix.rs b/crates/cqlib-core/src/qis/state/density_matrix.rs index 904e9f9a..a481d35b 100644 --- a/crates/cqlib-core/src/qis/state/density_matrix.rs +++ b/crates/cqlib-core/src/qis/state/density_matrix.rs @@ -504,8 +504,14 @@ impl DensityMatrix { } } Instruction::UnitaryGate(u_gate) => { + // Prefer an attached numeric matrix; otherwise resolve + // symbolic or circuit-backed definitions with this + // operation's parameter values. Both paths yield a + // gate-order matrix (first argument = MSB). if let Some(matrix) = u_gate.matrix() { dm.apply_unitary_gate(&qubit_indices, matrix)?; + } else if let Ok(matrix) = u_gate.matrix_for_params_in_gate_order(¶ms) { + dm.apply_unitary_gate(&qubit_indices, &matrix)?; } else { return Err(QisError::CircuitError(CircuitError::NoMatrixRepresentation)); } diff --git a/crates/cqlib-core/src/qis/state/density_matrix_noise.rs b/crates/cqlib-core/src/qis/state/density_matrix_noise.rs index 6aff31b0..3bbe28d4 100644 --- a/crates/cqlib-core/src/qis/state/density_matrix_noise.rs +++ b/crates/cqlib-core/src/qis/state/density_matrix_noise.rs @@ -284,9 +284,16 @@ impl DensityMatrixNoise { } } Instruction::UnitaryGate(u_gate) => { + // Prefer an attached numeric matrix; otherwise resolve + // symbolic or circuit-backed definitions with this + // operation's parameter values. Both paths yield a + // gate-order matrix (first argument = MSB). if let Some(matrix) = u_gate.matrix() { sim.apply_unitary_gate(&qs, matrix)?; sim.apply_noise(StandardGate::U, &qs)?; + } else if let Ok(matrix) = u_gate.matrix_for_params_in_gate_order(¶ms) { + sim.apply_unitary_gate(&qs, &matrix)?; + sim.apply_noise(StandardGate::U, &qs)?; } else { return Err(QisError::CircuitError( crate::circuit::CircuitError::NoMatrixRepresentation, diff --git a/crates/cqlib-core/src/qis/state/statevector.rs b/crates/cqlib-core/src/qis/state/statevector.rs index 21539d5e..42d2de38 100644 --- a/crates/cqlib-core/src/qis/state/statevector.rs +++ b/crates/cqlib-core/src/qis/state/statevector.rs @@ -604,8 +604,14 @@ impl Statevector { } } Instruction::UnitaryGate(u_gate) => { + // Prefer an attached numeric matrix; otherwise resolve + // symbolic or circuit-backed definitions with this + // operation's parameter values. Both paths yield a + // gate-order matrix (first argument = MSB). if let Some(matrix) = u_gate.matrix() { sv.apply_unitary_gate(&qubit_indices, matrix)?; + } else if let Ok(matrix) = u_gate.matrix_for_params_in_gate_order(¶ms) { + sv.apply_unitary_gate(&qubit_indices, &matrix)?; } else { return Err(QisError::CircuitError(CircuitError::NoMatrixRepresentation)); }