From 745fb081987e6f4cd052e9fc60529aadf13060d0 Mon Sep 17 00:00:00 2001 From: Chen Xinmiao Date: Wed, 21 Oct 2026 13:45:39 +0800 Subject: [PATCH 1/2] 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/2] 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",